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) {

本文详细探讨了Android中View的inflate方法,讲解了如何将XML布局转换为View对象。介绍了inflate的基本使用,包括不同重载方法的参数含义,并通过源码分析解释了inflate的内部工作原理,涉及LayoutInflater、rInflate和rInflateChildren的方法。文章最后提到,这些内容是理解View绘制体系的关键,后续将继续分享相关知识。
695

被折叠的 条评论
为什么被折叠?



