将一个layout文件实例化成一个View或ViewGroup就会用到LayoutInflater。
具体有两大类
第一大类(先获取LayoutInflater然后再inflate)
获取LayoutInflater有三种方法(其实后两种方法都是调用第一种方法)
- LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE); - LayoutInflater inflater = getLayoutInflater();
- LayoutInflater inflater = LayoutInflater.from(context);
inflate方法有四种方法(主要使用前两种,具体怎么使用放到后面讲)
- public View inflate(int resource, ViewGroup root)
- public View inflate(int resource, ViewGroup root, boolean attachToRoot)
- public View inflate(XmlPullParser parser, ViewGroup root)
- public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
第二大类(直接调用View.inflate)
View.inflate(Context context, int resource, ViewGroup root)
查看源码会发现,其实这个方法会调用LayoutInflater.from(context),也就是说最后还是调用
getSystemService(Context.LAYOUT_INFLATER_SERVICE)。
所以加上第一大类的三种方法,归根结底四种方法最后都要调用
getSystemService(Context.LAYOUT_INFLATER_SERVICE)。
解释下几个参数
resource:layout文件
root:被inflate的view的父view
attachToRoot:是否添加到父view。如果为true,就不需要通过addView来添加到父view。
注意点
通过源码查看root的解释
A view group that will be the parent. Used to properly inflate the layout_* parameters.
也就是说没有指定root的话,layout参数就失效了。
比如layout文件中指定height为100dp,但是没有指定root的话,是没有效果的。
但是有时候,需要对view作一些操作再添加到父view。不指定root的话,layout参数又没有效果。怎么办呢?这时候就可以用下面的方法了:
inflate(int resource, ViewGroup root, boolean attachToRoot)
将attachToRoot设为false就OK了。