志在巅峰的攀登者,不会陶醉在沿途的某个脚印之中,在码农的世界里,优美的应用体验,来源于程序员对细节的处理以及自我要求的境界,年轻人也是忙忙碌碌的码农中一员,每天、每周,都会留下一些脚印,就是这些创作的内容,有一种执着,就是不知为什么,如果你迷茫,不妨来瞅瞅码农的轨迹。

LayoutInflater 是用来将 layout.xml 布局文件添加到指定 View 中,或者是将 layout.xml 布局文件转化为对应的 View 对象。


1 LayoutInflater 的获取方式

第一种方式: 从给定的上 Context 下文中获取LayoutInflater:

LayoutInflater  inflater = LayoutInflater.from(context);

或者是

LayoutInflater inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

第二种方式:在Activity中直接获取LayoutInflater:

LayoutInflater inflater = getLayoutInflater();

从源码分析的角度,无论哪种方式,最终都是使用的 context.getSystemService 这种方式。

2 获取View

2.1 View.inflate

我们通常会将 layout 布局文件加载成View , 会这样来写

/**
* 将 Layout 文件 加载 View
* 参数一 上下文对象
* 参数二 布局文件 ID
* 参数三 不为null 时自动将这个布局文件 加载到这个 root 中去 null 代表不添加
*/
View inflate = View.inflate(mContext, R.layout.activity_list1_item, null);

它调用的源码如下

/**
* 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, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}

所以它实际上还是调用的 LayoutInflater.inflate 方法实现的加载。

2.2 LayoutInflater.inflate

/**
* 参数一 上下文对象
*/
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
/**
* 将 Layout 文件 加载 View
* 参数一 布局文件 ID
* 参数二 不为null 时 会测量这个 parent 的大小来 作为 inflate 的父组件大小参考
* 参数三 true 将加载的 layout 布局文件 自动添加到 parent 中去
*/
View inflate = layoutInflater.inflate(R.layout.activity_list1_item, parent,false);