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

如何在RecyclerView Adapter的点击监听器中显示AlertDialog并解决闪退问题

Android点击删除按钮弹出AlertDialog崩溃解决方案

核心故障原因

AlertDialog 创建要求传入Activity 类型的上下文,90% 以上的此类报错都是因为你给 Adapter 传入的 mCtx 是 Application 级别的全局上下文,不符合 AlertDialog 的窗口挂载要求,会直接触发 WindowManager 相关异常导致崩溃。

修复方案

1. 替换上下文来源

初始化 Adapter 时,传入所属 Activity 的实例作为 mCtx,不要用 getApplicationContext() 等方法获取全局上下文。如果是在 Activity 中初始化 Adapter,直接传 this 即可。

2. 添加上下文有效性校验

创建 Dialog 前先判断当前上下文是否有效,避免 Activity 已销毁后触发异常,同时建议使用 AndroidX 兼容库的 AlertDialog 提升多版本适配稳定性,修改后代码如下:

holder.delete.setOnClickListener(new View.OnClickListener() {
    String productId = String.valueOf(item.getId());
    @Override
    public void onClick(View v) {
        // 校验上下文有效性,避免Activity销毁后操作崩溃
        if (mCtx == null || (mCtx instanceof Activity && (((Activity) mCtx).isFinishing() || ((Activity) mCtx).isDestroyed()))) {
            return;
        }
        // 建议导入androidx.appcompat.app.AlertDialog使用兼容版Dialog
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mCtx);
        alertDialog.setTitle("App Name");
        alertDialog.setMessage("Are you sure you want to delete this item?");
        alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteItem(productId);
                dialog.dismiss();
            }
        });
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = alertDialog.create();
        dialog.show();
    }
});

注意:如果当前导入的是系统原生 android.app.AlertDialog,替换为 AndroidX 兼容包的 AlertDialog 可解决大部分低版本系统主题适配导致的崩溃问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:39:03