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

Android AlertDialog内嵌CheckBox调用isChecked始终返回false如何解决

问题原因

你调用的findViewById(R.id.checkbox)是当前Activity的方法,会优先从Activity加载的布局树里查找控件,而你要获取的CheckBox是在单独inflate出来的AlertDialog自定义布局view对象里,所以原代码要么找不到对应控件返回null,要么找到的是Activity布局里同名的其他CheckBox,自然获取不到弹窗里的勾选状态,所以返回值始终为false。

解决方法

修改PositiveButton点击事件中查找CheckBox的逻辑,从你之前inflate得到的弹窗自定义布局对象view上调用findViewById查找控件即可。

修正后的代码

AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AlertDialogTheme);

builder.setTitle("Delete Completed Tasks:");
View view = getLayoutInflater().inflate(R.layout.del_completed,null);

builder.setView(view);

builder.setPositiveButton("Delete",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 改动点:从弹窗的自定义布局view中查找对应CheckBox
                CheckBox cb = view.findViewById(R.id.checkbox);

                if(cb.isChecked()){
                    helper.delCompAndRec();
                }
                else helper.delCompleted();
            }
        });

builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){

    @Override
    public void onClick(DialogInterface dialogInterface, int i) {

    }
});

AlertDialog alert = builder.create();
alert.show();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:54:00