I get the lint warning, Avoid passing null as the view root
when inflating views with null
as parent
, like:
LayoutInfl
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:
inflate(int resource, ViewGroup root, boolean attachToRoot)
. Set attachToRoot
to false
.This tells the inflater that the parent is not available.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.
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)
.
According to https://developer.android.com/guide/topics/ui/dialogs
Inflate and set the layout for the dialog
Pass null as the parent view because its going in the dialog layout
therefore, for creating AlertDialog, I use @SuppressLint("InflateParams")
LayoutInflater inflater = requireActivity().getLayoutInflater();
@SuppressLint("InflateParams")
View view = inflater.inflate(R.layout.layout_dialog, null);
builder.setView(view);
Use this code to inflate the dialog view without a warning:
View.inflate(context, R.layout.dialog_edit, null);
From the documentation of View.inflate()
, it says
Inflate a view from an XML resource. This convenience method wraps the
LayoutInflater
class, which provides a full range of options for view inflation.
@param context The Context object for your activity or application.
@param resource The resource ID to inflate
@param root A view group that will be the parent. Used to properly inflate the layout_* parameters.
Instead of doing
view = inflater.inflate(R.layout.list_item, null);
do
view = inflater.inflate(R.layout.list_item, parent, false);
It will inflate it with the given parent, but won't attach it to the parent.
Many thanks to Coeffect (link to his post)