Android 布局填充器之LayoutInflater必知细节

概述

LayoutInflater主要用于加载布局.如在Activity中:setContentView(@LayoutRes int layoutResID);,
在Fragment中:onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);,在自定义View中,LayoutInflater.from(getContext()).inflate(resource,root,attachToRoot);

inflate的四种方式

//1.通过系统服务获取布局加载器
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(resource,root,attachToRoot);

//2.通过activity中的getLayoutInflater()方法
View view = getLayoutInflater().inflate(resource,root,attachToRoot);


//3.通过View的静态inflate()方法
View view = View.inflate(resource,root,attachToRoot);


//4.通过LayoutInflater的inflate()方法
View view = LayoutInflater.from(context).inflate(resource,root,attachToRoot);

四种方式的区别和联系

Activity:

 @NonNull
    public LayoutInflater getLayoutInflater() {
        return getWindow().getLayoutInflater();
    }

Activity调用了抽象类Window(即PhoneWindow)的方法。

public PhoneWindow(Context context)
{   
 super(context);   
    mLayoutInflater = LayoutInflater.from(context);
}

PhoneWindow的构造方法中静态调用的方式.获取LayoutInflater实例

View:

 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

也是静态调用获取实例,都是走的第四种方式.

LayoutInflater:

LayoutInflater是一个抽象类

public abstract class LayoutInflater extends Object

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;
    }

最终调用的也是
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);.

setContentView

 public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }
 @Override
    public void setContentView(int layoutResID) {
        if (mContentParent == null) {
            installDecor();
        } else {
            mContentParent.removeAllViews();
        }
        mLayoutInflater.inflate(layoutResID, mContentParent);
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
    }

在mContentParent为空的时候installDecor(DecorView),否则,移除所有的子View ,并将layoutResID通过inflate加载出来添加到mContentParent之中.CallBack就是当前Activity,

inflate重载方法

通过查看API文档,我们知道LayoutInflater.inflate有几种重载方法

public View inflate (int resource, ViewGroup root) 
public View inflate (XmlPullParser parser, ViewGroup root)
public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)  
public View inflate (int resource, ViewGroup root, boolean attachToRoot)

一般情况下.我们不会使用第二和第三种,通过查询源码,发现最终调用的都是第三种方式.

public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
        return inflate(parser, root, root != null);
    }

第一种内部掉用第四种

 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) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                    + Integer.toHexString(resource) + ")");
        }

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

LayoutInflater$inflate源码

    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            //...
            View result = root;

            try {
                // ...
                if (TAG_MERGE.equals(name)) {
                    //         ...
                } else {
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    //root != null,得到相应的ViewGroup.LayoutParams
                    if (root != null) {
                        //          ...
                        params = root.generateLayoutParams(attrs);
                        // attachToRoot == false,将root 的LayoutParams设置给temp
                        if (!attachToRoot) {

                            temp.setLayoutParams(params);
                        }
                    }
                    //attachToRoot == true && root != null,将temp加入到root这个viewGroup中
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }
                    // root == null || attachToRoot == false,直接返回temp
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
                //     ....
            }

            return result;
        }
    }

总结

假设我们inflate 出 resId后得到view为temp,

  1. 如果root为null,attachToRoot将失去作用,需要调用root.addView(temp)才能设置LayoutParams,返回temp。
  2. 如果root不为null,attachToRoot设为true,则相当于执行root.addView(temp, params);返回root。
  3. 如果root不为null,attachToRoot设为false,则相当于执行emp.setLayoutParams(params);返回temp。
  4. 如果root不为null,attachToRoot默认为true。

场景

  • 在自定义View的时候,我们一般直接将 布局文件直接添加到 root中,则会用到
// 此时attachToRoot 为默认值,true
public View inflate (int resource, ViewGroup root) ;
  • RecyclerviewonCreateViewHolder以及fragment的onCreateView中,则attachToRoot必须为false
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(getActivity());
    View view = inflater.inflate(android.R.layout.list_item_recyclerView, parent, false);
    return new ViewHolder(view);
}

解释: 因为展示Item的工作是交给LayoutManager来完成的, 而添加,移除 fragment的操作则是FragmentManager完成的.

参考:
Android LayoutInflater原理分析,带你一步步深入了解View(一)

Understanding Android’s LayoutInflater.inflate()

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值