Android中的LayoutInflater

将一个layout文件实例化成一个View或ViewGroup就会用到LayoutInflater。
具体有两大类

第一大类(先获取LayoutInflater然后再inflate)

获取LayoutInflater有三种方法(其实后两种方法都是调用第一种方法)

  1. LayoutInflater inflater = (LayoutInflater)
    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  2. LayoutInflater inflater = getLayoutInflater();
  3. LayoutInflater inflater = LayoutInflater.from(context);

inflate方法有四种方法(主要使用前两种,具体怎么使用放到后面讲)

  1. public View inflate(int resource, ViewGroup root)
  2. public View inflate(int resource, ViewGroup root, boolean attachToRoot)
  3. public View inflate(XmlPullParser parser, ViewGroup root)
  4. 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了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容