安卓源码分析——LayoutInflater(下)

安卓源码分析——LayoutInflater(上)

安卓源码分析——LayoutInflater(下)

1 前言

在安卓源码分析——LayoutInflater(上)中,我们通过对LayoutInflater的源码分析得出最终获取到的LayoutInfalter对象为PhoneLayoutInflater。那么接下来我们将继续剖析LayoutInflater是如何加载布局的。

2 PhoneLayoutInflater

public class PhoneLayoutInflater extends LayoutInflater {

    //安卓内置View类型的包名的前缀
    //TextViwe的全路径名称为android.widget.TextView
    //WebView的全路径名为android.webkit.WebView
    //android.app.为新增的前缀名
    private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };

    public PhoneLayoutInflater(Context context) {
        super(context);
    }

    protected PhoneLayoutInflater(LayoutInflater original, Context newContext) {
        super(original, newContext);
    }

    @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
        for (String prefix : sClassPrefixList) {
            try {
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {
              
            }
        }

        return super.onCreateView(name, attrs);
    }

    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}


PhoneLayoutInflater主要是重写了LayoutInflateronCreateView()方法。并调用了createView()方法。

3 布局加载inflate

LayoutInflater加载布局使用inflate()方法。

    
    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) + ")");
        }
        // 获取Xml文件的解析器, Resources类中调用ResourcesImpl的loadXmlResourceParser()方法
        //ResourcesImpl的loadXmlResourceParser()方法调用的XmlBlock的newParser()方法。
        //XmlBlock中newParser()方法调用nativeCreateParseState()本地方法最终创建Xml解析器
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

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


   
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    
        //此处为同步代码
        synchronized (mConstructorArgs) {
            
             
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;

            try {
                // 寻找Xml文件的根节点
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
  
                }

                //若没有根节点则抛出异常
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }

                //获取Xml解析器名称
                final String name = parser.getName();

              
                // 解析merge标签
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException(" can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    //如果是merge标签调用rInflate()方法解析
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // 如果不是merge标签,直接解析布局中的视图
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            //如果attachToRoot为false则为temp设置布局参数
                            temp.setLayoutParams(params);
                        }
                    }

                    
                    // 加载标签内部子布局
                    rInflateChildren(parser, temp, attrs, true);

                    // 如果root不为空并且attachToRoot为true则将temp添加至root视图
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // 如果root为空并且attachToRoot为false则直接返回temp视图
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } 
            //省略部分代码

            
            return result;
        }
    }

4 rInflate 方法

rInflate()方法用于加载merge标签的布局。

void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

        //获取树的深度,采用的是树的深度优先遍历方法
        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;

        
        //按照顺序解析布局元素
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();

            if (TAG_REQUEST_FOCUS.equals(name)) {
            
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) { // 解析include标签
                if (parser.getDepth() == 0) {
                    //如果树深度为0,且根为include 则抛出此异常
                    throw new InflateException(" cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                //如果merge标签不为根,则抛出此异常
                throw new InflateException(" must be the root element");
            } else {
            
                //根据元素标签名称进行解析
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                
                //解析内部子标签
                rInflateChildren(parser, view, attrs, true);
                将解析结果View添加至其父布局中
                viewGroup.addView(view, params);
            }
        }

        //省略部分代码
    }

rInflate()通过深度优先搜索方式构造View树,每解析到一个View就会递归加载下去,直至该路径下的View都加载完毕,然后将此路径下的View添加至父布局中。rInflate()加载元素调用了createViewFromTag()方法。

5 createViewFromTag方法

createViewFromTag()用于解析具体某个View元素。


    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }

        // Apply a theme wrapper, if allowed and one is specified.
        if (!ignoreThemeAttr) {
            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
            final int themeResId = ta.getResourceId(0, 0);
            if (themeResId != 0) {
                context = new ContextThemeWrapper(context, themeResId);
            }
            ta.recycle();
        }

        if (name.equals(TAG_1995)) {
            // Let's party like it's 1995!
            return new BlinkLayout(context, attrs);
        }

        try {
            View view;
            
            //用户可以通过设置LayoutInflater的Factory来自行解析View,但是大部分开发人员没有这么做
            //mFactory2、mFactory、mPrivateFactory默认为空值,因此可以暂时忽略此处代码。
            if (mFactory2 != null) {
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }

            if (view == null && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }

            
            
            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    if (-1 == name.indexOf('.')) {
                        //解析内置View,因为内置的View中不包含.字符
                        view = onCreateView(parent, name, attrs);
                    } else {
                        // 解析自定义View
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
        } 
        //省略部分代码
    }

通过分析发现onCreateView()最终仍是调用createView()实现View的解析的。因此我们只需查看createView()方法。

6 createView

createView()实现View的最终创建过程。


    public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
            
        //从缓存中获取构造方法
        Constructor constructor = sConstructorMap.get(name);
        
        //缓存中构造方法不为空,但是判断类加载是不是由LayoutInflater委派的,则从缓存中删除此构造方法
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class clazz = null;

        try {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);

            if (constructor == null) {
                // Class not found in the cache, see if it's real, and try to add it
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);

                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                
                
                //从 Class对象中获取构造方法
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                //将构造方法加入缓存
                sConstructorMap.put(name, constructor);
            } else {
                // If we have a filter, apply it to cached constructor
                if (mFilter != null) {
                    // Have we seen this name before?
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) {
                        // 新的类型,则加载该类,并记录其加载状态
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);

                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
            }

            Object lastContext = mConstructorArgs[0];
            if (mConstructorArgs[0] == null) {
                // Fill in the context if not already within inflation.
                mConstructorArgs[0] = mContext;
            }
            Object[] args = mConstructorArgs;
            args[1] = attrs;

            //通过反射的方式实现View对象的创建
            final View view = constructor.newInstance(args);
            if (view instanceof ViewStub) {
                // Use the same context when inflating ViewStub later.
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            mConstructorArgs[0] = lastContext;
            return view;

        } 
        
        //省略catch 和 finally代码块
    }

createView()根据类名通过反射的方式实现View对象的创建。并且在创建同时将View类的构造函数添加至缓存,可以提高View的加载效率。

7 小结

布局的加载首先判断根布局的标签,根据不同根布局分开解析。不带有子布局的直接解析,带有子布局的递归解析。根据Xml解析出的标签名称得出类名,最终对于View对象的创建根据类名通过反射的方式实现,最终实现布局的完全加载。

你可能感兴趣的:(安卓源码分析——LayoutInflater(下))