“Avoid passing null as the view root” warning when inflating view for use by AlertDialog

前端 未结 10 678
面向向阳花
面向向阳花 2020-12-12 15:41

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

LayoutInfl         


        
相关标签:
10条回答
  • 2020-12-12 16:45

    Casting null as ViewGroup resolved the warning:

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

    where li is the LayoutInflater's object.

    0 讨论(0)
  • 2020-12-12 16:45

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

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

    0 讨论(0)
  • 2020-12-12 16:45

    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);
    
    0 讨论(0)
  • 2020-12-12 16:45
    1. The AlertDialog is as far as I know the only case were you can safely use null instead of a parent view. In this case you can suppress the warning by using:

      @SuppressLint("InflateParams")

    2. In general you should never use SupressLint or one of the workarounds mentioned in the other answers to get rid of the warning. The parent view is necessary to evaluate the Layout Params which are declared in the root element of the View being inflated. That means if you use null instead of the parent view, all Layout Params in the root element will be ignored and replaced by default Layout Params. Most of the time it will be fine, but in some cases it will result in a really hard-to-find bug.

    0 讨论(0)
提交回复
热议问题