You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android onClick触发异常:Restart按钮崩溃、Exit按钮无响应

问题分析与解决方案

1. Restart按钮抛出异常的原因及解决

异常日志核心提示:android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.breakoutgame/com.example.breakoutgame.Game}; have you declared this activity in your AndroidManifest.xml?

这说明**Game类对应的Activity未在AndroidManifest.xml中注册**,Android系统无法识别并启动该页面。

解决步骤:

打开项目根目录下的AndroidManifest.xml文件,在<application>标签内部添加GameActivity的注册代码:

<activity
    android:name=".Game"
    android:exported="true" />

注:如果Game类不在默认包路径下,需要填写完整类名(如com.example.breakoutgame.Game);Android 12及以上版本必须添加android:exported属性。

2. Exit按钮无响应的排查方向

Exit按钮逻辑为调用finish()关闭当前页面,无响应通常由以下问题导致:

  • 方法名不匹配:检查布局中Exit按钮的android:onClick="exit"是否与GameOver类中exit(View view)的方法名完全一致(大小写敏感)
  • 视图遮挡:确认布局中没有其他View覆盖在Exit按钮上方,导致点击事件无法触发
  • 方法权限错误:确保exit()方法是public修饰,且参数为View view(参数类型、数量不能修改)

更可靠的替代方案:代码绑定点击事件

如果android:onClick方式容易出问题,建议改用代码绑定,步骤如下:

  1. 给布局中的两个ImageButton添加id属性:
<ImageButton
    android:id="@+id/btn_exit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/exit" />

<ImageButton
    android:id="@+id/btn_restart"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/restart" />
  1. 在GameOver类的onCreate()方法中绑定点击事件:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_game_over_layout); // 替换为你的布局文件名

    ImageButton exitBtn = findViewById(R.id.btn_exit);
    exitBtn.setOnClickListener(v -> finish());

    ImageButton restartBtn = findViewById(R.id.btn_restart);
    restartBtn.setOnClickListener(v -> {
        Intent intent = new Intent(GameOver.this, Game.class);
        startActivity(intent);
        finish();
    });
}

内容的提问来源于stack exchange,提问作者zygisk123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:20:17