Android: What is the difference between View.inflate and getLayoutInflater ().

What's the difference between:

return context.getLayoutInflater().inflate(R.layout.my_layout, null); 

Fill the new view hierarchy from the specified xml resource.

and

 return View.inflate(context, R.layout.my_layout, null); 

Click a view from an XML resource. This convenience method wraps the LayoutInflater class, which provides a full range of options for inflation of views.

+5
source share
2 answers

Both are the same. The second version is just a convenient and short method for completing a task. If you see the source code of the View.inflate() method, you will find:

  /** * Inflate a view from an XML resource. This convenience method wraps the {@link * 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. * @see LayoutInflater */ public static View inflate(Context context, int resource, ViewGroup root) { LayoutInflater factory = LayoutInflater.from(context); return factory.inflate(resource, root); } 

Which actually does the same job in the backend as the 1st method you mentioned.

+6
source

They are the same and do the same.

In View.java class

 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { LayoutInflater factory = LayoutInflater.from(context); return factory.inflate(resource, root); } 

and LayoutInflater.from(context) to return the LayoutInflator object. which is similar to calling getLayoutInflator() .

 public static LayoutInflater from(Context context) { LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (LayoutInflater == null) { throw new AssertionError("LayoutInflater not found."); } return LayoutInflater; } 
+1
source

Source: https://habr.com/ru/post/1243560/


All Articles