美文网首页
Android inflate原理剖析

Android inflate原理剖析

作者: 詠遠鍀飛哥 | 来源:发表于2018-08-08 17:50 被阅读13次

    1.inflate方法的调用存在于两个类中

    1. 使用View中的静态方法View.inflate()方法:
    
    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }
    
    1. 使用LayoutInflate中的inflate()方法,在LayoutInflater类中有几个重载方法:
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root)
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
    
    最终调用的都是iinflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)这个方法
    

    2.获取inflate()方法的途径有三种

    1.public static LayoutInflater from(Context context)
    2.LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
    3.在Activity中 public LayoutInflater getLayoutInflater()

    • Activity getLayoutInflater继承自PhoneWindow的getLayoutInflate方法,最终调用的是LayoutInflater.from(context);

    • LayoutInflater中的from方法中通过getSystemService()方法获取LayoutInflate对象

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

    3.root参数和attachToRoot参数

    1. root = null 不管attchToRoot,只是创建视图;
    2. root != null && attchToRoot = ture 初始化视图,并且将视图添加到root中;
    3. root != null && attchToRoot = false, 初始化视图,布局所有做外层属性生效,相当于设置了layoutParam参数;
    4. 在不设置attachToRoot参数情况下,其等于attachToRoot = (root != null);

    相关文章

      网友评论

          本文标题:Android inflate原理剖析

          本文链接:https://www.haomeiwen.com/subject/cfuxbftx.html