View绘制体系(二)——View的inflate详解
前言
上一篇博客讲到setContentView
最后会调用mLayoutInflater.inflate
来创建了自定义xml中的布局视图,添加到mContentParent
中,这里我们就来学习下inflate
的具体实现以及它的基本使用方法。
inflate的基本使用
首先我们需要明确的是,inflate
方法是讲xml
文件反射成一个View
,但是并不执行View的绘制。
inflate
常用的重载有两种方式:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
所以我们只需要知道第二种重载的参数意义就OK了:
resource
:需要反射的xml文件的资源idroot
:关于root我们需要注意的是,它并不代表将创建好的布局加入到root中,而是表示将root作为父容器来创建指定的View。
将root作为父容器创建View,其含义是让root协助View的根节点生成布局参数,如果没有父容器的话,View的根节点的宽高属性(match_parent,wrap_parent等)将没任何的意义,即不会产生任何的效果
attachToRoot
:是否将创建好的View
添加到root
中
通常我们使用inflate
有以下三种方式:
LayoutInflater.inflate
:在获取到LayoutInflater
实例后,可以通过如下代码加载布局:
LayoutInflater inflater = LayoutInflater.from(this);
View view1 = inflater.inflate(R.layout.view1, null);
View view2 = inflater.inflate(R.layout.view2, null, false);
View.inflate
:只有一种形式如下:
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
其实质是通过LayoutInflater
来创建View的
Context.getSystemService
:通过Context.getSystemService
来获得LayoutInflater
,实质也是通过LayoutInflater
来创建View
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view1 = inflater.inflate(R.layout.view1, null);
inflate源码解析
现在我们就来详细的分析下inflate的整个流程,源码如下:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)