1.LayoutInflater.form方法
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
2.inflate方法
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
return inflate(parser, root, root != null);
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
return inflate(res.getLayout(resource), root, attachToRoot);
}
//这三个方法都调用第四个方法
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
// ....前面的都是一些非核心代码
final View temp = createViewFromTag(root, name, inflaterContext, attrs);//创建view
ViewGroup.LayoutParams params = null;
if (root != null) {//如果root!=null 则获取temp宽高信息
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {//如果attachToRoot==false 则temp设置宽高
temp.setLayoutParams(params);
}
}
if (root != null && attachToRoot) {//如果root!=null 并attachToRoot=true 直接添加view
root.addView(temp, params);
}
//如果root == null 或attachToRoot=true 直接返回view
if (root == null || !attachToRoot) {
result = temp;
}
}
return result;
}
}
3.总结
如果root!=null以及attachToRoot==false 则根据XML的根布局宽高设置根布局的宽高
如果root!=null 并attachToRoot=true 直接添加view(view也会根据XML的根布局宽高设置根布局的宽高)
如果root == null 或attachToRoot=true 直接返回view,不会设置根布局的宽高
1)RecyclerView的item
LayoutInflater.from(this).inflate(R.layout.xxx, parent, false)
2)直接添加
LayoutInflater.from(this).inflate(R.layout.xxx,父view,true);
4.AsyncLayoutInflater类
//封装了一个LayoutInflater,可异步加载
//因为LayoutInflater解析xml也是需要耗时的
new AsyncLayoutInflater(this).inflate(@LayoutRes int resid, @Nullable ViewGroup parent, @NonNull AsyncLayoutInflater.OnInflateFinishedListener callback);
//AsyncLayoutInflater异步加载完通过Handler发送消息
网友评论