如何在android中修复“避免将null作为视图根”?

时间:2014-12-26 22:48:37

标签: android android-alertdialog

在我的Android应用程序中,我创建了一个这样的对话框:

private void handleEdit() {
    LayoutInflater inflater = getLayoutInflater();
    View dialoglayout = inflater.inflate(R.layout.dialog_gallery, null);

    final AlertDialog d = new AlertDialog.Builder(this)
    .setView(dialoglayout)
    .setTitle(R.string.edit)
    .setNegativeButton(R.string.cancel, null)
    .create();

    CheckBox mainCB = (CheckBox)dialoglayout.findViewById(R.id.main);
    CheckBox usedCB = (CheckBox)dialoglayout.findViewById(R.id.used);
    mainCB.setChecked(image.getIsMain());
    usedCB.setChecked(image.getApproved());

    mainCB.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if (Network.isNetworkAvailable(GalleryScreen.this)) {
                new Async_update_image_state(GalleryScreen.this, fish, image, !image.getIsMain(), image.getApproved(), false);
                d.dismiss();
            } else {
                Popup.ShowErrorMessage(GalleryScreen.this, R.string.no_internet, false);
            }
        }
    });

    usedCB.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if (Network.isNetworkAvailable(GalleryScreen.this)) {
                new Async_update_image_state(GalleryScreen.this, fish, image, false, !image.getApproved(), true);
                d.dismiss();
            } else {
                Popup.ShowErrorMessage(GalleryScreen.this, R.string.no_internet, false);
            }
        }
    });

    d.show();
}

但我在View dialoglayout = inflater.inflate(R.layout.dialog_gallery, null);上发出警告,强调null

Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element)

这是什么意思,我该如何解决?

感谢。

4 个答案:

答案 0 :(得分:11)

这对我有用

View.inflate(getActivity(), R.layout.dialog, null);

没有任何警告或错误。

答案 1 :(得分:8)

在对对话框中使用布局进行充气时,可以安全地在此处传递null并忽略警告。

来自This Link

  

这里的问题是AlertDialog.Builder支持自定义视图,但是   没有提供采用布局的setView()实现   资源;所以你必须手动充气XML。但是,因为   结果将进入对话框,该对话框不会公开其根视图   (事实上​​,它还不存在),我们无法访问最终版本   布局的父级,所以我们不能用它来进行通货膨胀。事实证明,   这是无关紧要的,因为AlertDialog将删除任何LayoutParams   无论如何都要用match_parent替换它们。

答案 2 :(得分:1)

而不是:

inflater.inflate(R.layout.dialog_gallery, null);

做的:

inflater.inflate(R.layout.dialog_gallery, parent, false);

在上面的评论中使用@SuppressLint annotation建议的Eugen可以"取消"警告,但它没有解决问题。使用null作为ViewGroup的参数将导致您将来出现问题。

答案 3 :(得分:0)

而不是

inflater.inflate(R.layout.dialog_gallery, null);

inflater.inflate(R.layout.dialog_gallery, null, false);

它不会将视图附加到您的案例中为null的父级。

详见Android Reference