ramlife

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

问题

AlertDialog 第一次弹出来没问题,第二次弹出来就报这个错误。

分析

经过检查,因为有好几个输入框,所以使用的是 xml 自定义的一个 view,这个 view 在创建的时候初始化好了,然后在 button 的 点击中,会用 new 来创建 AlertDialog ,每点击一次,都新建一次。所以第二次的时候,会报错。
解决的方法也很简单,既然 view 只创建一次,那么 AlertDialog 也只创建一次就好了,在点击中只要 show 就可以了。

代码

        // 获取 fragment 的 content
        searchAlertBuilder = new AlertDialog.Builder(getContext());
        searchAlertBuilder.setView(view_dialog)
                .setTitle("搜索历史数据")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        searchData();
                    }
                })
                .setNegativeButton("否", null);
        searchAlert = searchAlertBuilder.create();


        searchLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchAlert.show();
            }

参考

如何在Fragment中获取context
https://blog.csdn.net/demonliuhui/article/details/51511136

The specified child already has a parent. You must call removeView() on the child's parent first.
https://blog.csdn.net/lxd_love_lgc/article/details/105650993

Android studio AlertDialog(对话框)详解
https://www.cnblogs.com/mjhjl/p/14902257.html

Android的AlertDialog详解(7种方式)
https://blog.csdn.net/shandong_chu/article/details/121945487

【Android基础篇】AlertDialog自定义setView方法的控件响应方法
https://blog.csdn.net/henreash/article/details/44559051

android中AlertDialog 中setView用法的一些小结
https://blog.csdn.net/lowtec_ljf/article/details/17198853

posted on 2022-08-10 21:34  ramlife  阅读(96)  评论(0编辑  收藏  举报