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

Android Studio中按钮点击应用崩溃问题排查及代码修复请求

崩溃原因排查与修复方案

核心问题分析

点击按钮崩溃的大概率原因是目标Activity未注册、控件ID不匹配或全屏设置冲突,以下是逐一修复步骤:


1. 注册所有目标Activity

启动ProfileActivity、RegisterActivity、ForgetPasswordActivity前,必须在AndroidManifest.xml的<application>标签内声明这些Activity,否则会触发ActivityNotFoundException:

<application
    ...>
    <activity android:name=".LoginActivity" />
    <!-- 添加以下三个Activity声明 -->
    <activity android:name=".ProfileActivity" />
    <activity android:name=".RegisterActivity" />
    <activity android:name=".ForgetPasswordActivity" />
</application>

2. 验证布局控件ID匹配

检查activity_login.xml中是否存在以下ID的控件,拼写必须完全一致,否则findViewById会返回null,点击时触发NullPointerException:

  • txt_signup2(TextView)
  • txt_3(TextView)
  • btnLogin(Button)

3. 简化全屏设置避免主题冲突

原代码中requestWindowFeature和getSupportActionBar().hide()可能与App主题冲突(比如主题已设置无ActionBar),简化全屏代码:

// 替换原全屏相关代码
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

4. 查看Logcat定位精准问题

打开Android Studio的Logcat窗口,筛选Error级别日志,根据崩溃栈轨迹快速定位:

  • ActivityNotFoundException:对应Activity未注册
  • NullPointerException:对应控件为空或未初始化
  • IllegalStateException:全屏设置与主题冲突

修复后的完整代码

package com.example.pnrcompanion;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 简化全屏设置,避免主题冲突
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);

        // 初始化控件,确保布局中存在对应ID
        TextView text1 = findViewById(R.id.txt_signup2);
        TextView text2 = findViewById(R.id.txt_3);
        Button btn1 = findViewById(R.id.btnLogin);

        // 登录按钮跳转
        btn1.setOnClickListener(v -> startActivity(new Intent(LoginActivity.this, ProfileActivity.class)));

        // 注册页面跳转
        text1.setOnClickListener(v -> startActivity(new Intent(LoginActivity.this, RegisterActivity.class)));

        // 忘记密码页面跳转
        text2.setOnClickListener(v -> startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity.class)));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:10:37