开发者社区> 问答> 正文

只要监听按钮就崩溃,给跪了啊。。。:报错


不知道为何,只要监听按钮就会崩溃,无解中。。怎么解决啊。

布局文件layout/dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/passord"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="请输入密码" />

    <Button
        android:id="@+id/ok"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="确认" />

</LinearLayout>

Java 代码
                AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialog, null);
        
        builder.setTitle("设置密码");
        builder.setView(view);
        dialog = builder.create();
        dialog.show();
        
        Button btn_ok = (Button) findViewById(R.id.ok);
        
        //这段是按钮监听代码
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            //没有任何内容也会崩溃,所以不是这里面的问题
            }
        });
        
只要监听按钮就崩溃,为什么!怎么解决啊

展开
收起
kun坤 2020-06-06 00:17:52 521 0
1 条回答
写回答
取消 提交回答
  • 会崩溃是对的,空指针异常btn_ok == null.

    把Button btn_ok = (Button) findViewById(R.id.ok);改为Button btn_ok = (Button) dialog.findViewById(R.id.ok);

    ######

    引用来自“该用户不存在”的评论

    会崩溃是对的,空指针异常btn_ok == null.

    把Button btn_ok = (Button) findViewById(R.id.ok);改为Button btn_ok = (Button) dialog.findViewById(R.id.ok);

    非常正确!问题已解决,谢谢!

    2020-06-06 00:17:56
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载