“Avoid passing null as the view root” warning when

2019-01-30 05:45发布

I get the lint warning, Avoid passing null as the view root when inflating views with null as parent, like:

LayoutInflater.from(context).inflate(R.layout.dialog_edit, null);

However, the view is to be used as the content of an AlertDialog, using setView on AlertDialog.Builder, so I don't know what should be passed as the parent.

What do you think the parent should be in this case?

7条回答
我命由我不由天
2楼-- · 2019-01-30 06:12

The short story is that when you are inflating a view for a dialog, parent should be null, since it is not known at View inflation time. In this case, you have three basic solutions to avoid the warning:

  1. Suppress the warning using an @Suppress
  2. Inflate the View using View's inflate method. This is just a wrapper around a LayoutInflater, and mostly just obfuscates the problem.
  3. Inflate the View using LayoutInflater's full method: inflate(int resource, ViewGroup root, boolean attachToRoot). Set attachToRoot to false.This tells the inflater that the parent is not available. In older versions of Android Lint, this removed the warning. This is no longer the case in post 1.0 versions of Android Studio.

Check out http://www.doubleencore.com/2013/05/layout-inflation-as-intended/ for a great discussion of this issue, specifically the "Every Rule Has an Exception" section at the end.

查看更多
Bombasti
3楼-- · 2019-01-30 06:15

Use this code to inflate the dialog view without a warning:

View.inflate(context, R.layout.dialog_edit, null);
查看更多
成全新的幸福
4楼-- · 2019-01-30 06:17

When you really don't have any parent (for example creating view for AlertDialog), you have no other choice than passing null. So do this to avoid warning:

final ViewGroup nullParent = null;
convertView = infalInflater.inflate(R.layout.list_item, nullParent);
查看更多
我命由我不由天
5楼-- · 2019-01-30 06:18

You should use AlertDialog.Builder.setView(your_layout_id), so you don't need to inflate it.

Use AlertDialog.findViewById(your_view_id) after creating the dialog.

Use (AlertDialog) dialogInterface to get the dialog inside the OnClickListener and then dialog.findViewById(your_view_id).

查看更多
萌系小妹纸
6楼-- · 2019-01-30 06:19

You don't need to specify a parent for a dialog.

Suppress this using @SuppressLint("InflateParams") at the top of the override.

查看更多
beautiful°
7楼-- · 2019-01-30 06:22

Casting null as ViewGroup resolved the warning:

View dialogView = li.inflate(R.layout.input_layout,(ViewGroup)null);

where li is the LayoutInflater's object.

查看更多
登录 后发表回答