1 LayoutInflater用于加载布局
LayoutInflater用于加载布局的。加载布局的任务通常都是在Activity中调用setContentView()方法来完成的。其实setContentView()方法的内部也是使用LayoutInflater来加载布局的,只不过这部分源码是内部的。先看下LayoutInflater的基本用法,首先需要获取到LayoutInflater的实例,有两种方法可以获取到:
// 第一种写法如下:
LayoutInflater layoutInflater = LayoutInflater.from(context);
// 还有另外一种写法也可以完成同样的效果:
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 得到了LayoutInflater的实例之后就可以调用它的inflate()方法来加载布局了,如下所示:
layoutInflater.inflate(resourceId, root);
2 View.inflate和LayoutInflater.inflate效果的区别
(1)平时Recyclerview加载item中,adapter的getView方法中,我们经常用到LayoutInflater.inflate这样的方法来加载布局xml,平时一直就是这么用的,也没什么疑问。
LayoutInflater.from(mContext).inflate(R.layout.item_consume_recharge_record, parent, false);
(2)一次在加载布局时,使用了如下的方法View.inflate加载布局:
@Override
public ConsumeRechargeRecordViewHolder onCreateViewHolder_(ViewGroup parent, int viewType) {
View itemView = View.inflate(mContext, R.layout.item_consume_recharge_record, null);
return new ConsumeRechargeRecordViewHolder(itemView);
}
得到的效果如下,没有将item的布局文件最外层的所有layout属性设置:
(