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?
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 the View using LayoutInflater's full method:In older versions of Android Lint, this removed the warning. This is no longer the case in post 1.0 versions of Android Studio.inflate(int resource, ViewGroup root, boolean attachToRoot)
. SetattachToRoot
tofalse
.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.
Use this code to inflate the dialog view without a warning:
When you really don't have any
parent
(for example creating view forAlertDialog
), you have no other choice than passingnull
. So do this to avoid warning: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 thedialog
inside theOnClickListener
and thendialog.findViewById(your_view_id)
.You don't need to specify a
parent
for a dialog.Suppress this using
@SuppressLint("InflateParams")
at the top of the override.Casting null as ViewGroup resolved the warning:
where
li
is theLayoutInflater's
object.