Android View对象创建流程分析

2019-09-21  本文已影响0人  酷酷的Demo

写作背景

在Android源码实现部分,很多人都应该分析过View的绘制流程,measure,layout,draw三个过程也许已经十分熟悉了,但是相信有很多小伙伴和笔者一样并不知道到xml布局到底是如何被解析然后转换成View的,今天笔者将和大家一起来学习这个流程(基于Android API 28源码)。

View加载的调用

在Android开发过程中,使用XML文件编写UI界面后,通常我们会调用setContentView(resId)或者LayoutInflater.inflate(resId,...)的方式把布局文件加载到Activity中,并实现视图与逻辑的绑定与开发。

Activity的setContentView

setContentView方法大家都已经非常熟悉了,无论是系统原生的Activity还是V7或V4包下的其他子类Activity,在onCreate方法中一般都会调用到这个方法,下面来看看源码:

public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }
public Window getWindow() {
    return mWindow;
}

由于之前已经分析过Window,所以这里就不再赘述,我们关注本文的重点部分setContentView,在Activity的setContentView方法里传递给了PhoneWindow的setContentView方法来执行布局的加载。

getWindow()方法返回的是一个Window对象,具体是其实现类PhoneWindow对象,对应的是mWindow字段。这里简单提一下,不清楚的可以看笔者的这篇文章

现在继续关注PhoneWindow的setContentView源码:

    @Override
    public void setContentView(int layoutResID) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        if (mContentParent == null) {
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
         // 将View添加到DecorView的mContentParent中
         // 调用LayoutInflater的inflate方法解析布局文件,并生成View树,mContentParent为View树的根节点
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        
        //回调Activity的onContentChanged方法通知视图发生改变
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

这里也比较清楚,当我们没有设置转场动画的会执行mLayoutInflater.inflate(layoutResID, mContentParent),而这个mLayoutInflater是在PhoneWindow的构造方法中被实例的:

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

所以我们可以得出结论Activity的setContentView方法最终就是通过 LayoutInflater.from(context).inflate(resId, ……) 来实现布局的解析然后加载出来的.而其他子类Activity虽然可能复写了setContentView方法,但还是可以发现其最终的实现方式是一样的,这里看一下v7包下的AppCompatActivty的setContentView方法:

@Override
public void setContentView(@LayoutRes int layoutResID) {
    getDelegate().setContentView(layoutResID);
}

//android.support.v7.app.AppCompatDelegateImplV9.setContentView(resId)
@Override
public void setContentView(int resId) {
    ensureSubDecor();
    ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
    contentParent.removeAllViews();
    LayoutInflater.from(mContext).inflate(resId, contentParent);
    mOriginalWindowCallback.onContentChanged();
}

果然不出意外,这里又出现了了LayoutInflater的身影。所以进一步得出结论:xml文件是用LayoutInflater的inflate方法来实现解析与加载的

LayoutInflater如何实例化

看一下源码中的LayoutInflater是怎样介绍的:

/**
 * Instantiates a layout XML file into its corresponding {@link android.view.View}
 * objects. It is never used directly. Instead, use
 * {@link android.app.Activity#getLayoutInflater()} or
 * {@link Context#getSystemService} to retrieve a standard LayoutInflater instance
 * that is already hooked up to the current context and correctly configured
 * for the device you are running on.
 *
 * <p>
 * To create a new LayoutInflater with an additional {@link Factory} for your
 * own views, you can use {@link #cloneInContext} to clone an existing
 * ViewFactory, and then call {@link #setFactory} on it to include your
 * Factory.
 *
 * <p>
 * For performance reasons, view inflation relies heavily on pre-processing of
 * XML files that is done at build time. Therefore, it is not currently possible
 * to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
 * it only works with an XmlPullParser returned from a compiled resource
 * (R.<em>something</em> file.)
 */
@SystemService(Context.LAYOUT_INFLATER_SERVICE)
public abstract class LayoutInflater {···}

从注释的第一行我们也可以发现LayoutInflater是用来实例化一个XML
文件到对应的View对象的一个类,并且并不希望被直接使用,而是通过Activity的getLayoutInflater()方法或者Context的getSystemService()来或取一个标准的LayoutInflater对象。在类上面的注释我们也可以发现使用Context.LAYOUT_INFLATER_SERVICE通过getSystemService方法来获取。最后再看这个类,发现是一个抽象类,抽象类是不能够被实例化的,所以这也就会出现注释中所写的两种方法来获取实例了:

Activity的getLayoutInflater

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

这里就可以发现Activity获取LayoutInflater是通过PhoneWindow的getLayutInflater方法来获取的,最终的到的对象就是PhoneWindow中的mLayoutInflater;而这个mLayoutInflater上文也介绍过,是通过LayoutInflater.from(context)方法来创建的:

 /**
     * Obtains the LayoutInflater from the given context.
     */
    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;
    }

首先看方法的注释:从给定的上下文中获取LayoutInflater,然后在看代码的具体实现。看过这段代码相信大家已经有了答案。没错,事实的真相只有一个,那就是通过服务获取LayoutInflater实例对象。那么现在该继续深入context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法的具体实现了:

由于Context的实现类是ContextImpl,所以实际调用的是它的方法:

 @Override
    public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }
//SystemServiceRegistry.class
 /**
     * Gets a system service from a given context.
     */
    public static Object getSystemService(ContextImpl ctx, String name) {
        ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
        return fetcher != null ? fetcher.getService(ctx) : null;
    }

在ContextImpl的getSystemService方法中调用了SystemServiceRegistry的getSystemService方法,根据这个类的命名可以猜测这是一个提供系统服务注册的类,在这个类的代码中我们发现非常多的服务的注册工作,就像这样:

static {
        registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
                new CachedServiceFetcher<AccessibilityManager>() {
            @Override
            public AccessibilityManager createService(ContextImpl ctx) {
                return AccessibilityManager.getInstance(ctx);
            }});

        registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
                new CachedServiceFetcher<CaptioningManager>() {
            @Override
            public CaptioningManager createService(ContextImpl ctx) {
                return new CaptioningManager(ctx);
            }});
            ···
}

/**
     * Statically registers a system service with the context.
     * This method must be called during static initialization only.
     */
    private static <T> void registerService(String serviceName, Class<T> serviceClass,
            ServiceFetcher<T> serviceFetcher) {
        SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
        SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
    }

这里有大量的服务注册工作,所以省略了大量代码,现在来看看要通过Context.LAYOUT_INFLATER_SERVICE获取的服务是如何被注册的:

    ···
     registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
                new CachedServiceFetcher<LayoutInflater>() {
            @Override
            public LayoutInflater createService(ContextImpl ctx) {
                return new PhoneLayoutInflater(ctx.getOuterContext());
            }});
    ···

显然我们想要获取的服务就是这里提前注册过的服务,也就是一个PhoneLayoutInflater对象,之前就说过LayoutInflater是一个抽象类,现在终于找到了它的实现类了。

LayoutInflater读取xml文件并创建View

通过LayoutInflater.from(context)获取到了LayoutInflater实例后,现在要调用它的inflate方法来实现xml文件的读取与View的创建:

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) {
        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();
        }
    }

可以看到这里有三个inflate的重载方法,但是比较重要的就是后一个,主要是通过Resourse对象通过getLayout方法将resId转换成一个XmlResourceParser对象,然后又调用了一个inflate方法:

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 {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                ```

                final String name = parser.getName();
                ···
                //第一部分merge标签
                //内部静态常量private static final String TAG_MERGE = "merge";
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                
                //另一部分
                } else {
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                       ···
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

                    ···
                    // Inflate all children under temp against its context.
                    rInflateChildren(parser, temp, attrs, true);
                    ···
                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
                ···
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;

                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            return result;
        }
    }

这一个inflater方法也就是最重要的inflater方法了,首先遍历XmlPullParser对象,寻找根节点,并赋值给type。找到根节点后的实现比较长,这里分成了两个部分来讲,分别是merge部分和其他view部分。

merge标签

首先根据标签名判断是否是merge标签,如果是merge标签则根节点不能为null并且attachToRoot必须为true,否则抛出异常,这很容易理解因为使用merge标签的xml布局需要依附在一个父布局之下,然后会调用rInflater方法:

 void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        //获取View树的深度 深度优先遍历
        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();

            // 内部定义的静态常量:
            //private static final String TAG_REQUEST_FOCUS = "requestFocus";
            if (TAG_REQUEST_FOCUS.equals(name)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
                
            // private static final String TAG_TAG = "tag";
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
                
            // 解析include标签
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            //如果是merge标签 抛出异常 因为merge标签必须为根视图
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> 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);
                viewGroup.addView(view, params);
            }
        }

        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }

        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

首先会遍历整个节点,子节点会有"requestFocus"、"tag"、""、"include",但是不能有"merge",因为merge标签只能为这里的根元素,除此之外的View标签会通过createViewFromTag方法创建View,实际上"include"标签也会创建view,我们看parseInclude方法:

private void parseInclude(XmlPullParser parser, Context context, View parent,
            AttributeSet attrs) throws XmlPullParserException, IOException {
        int type;

        if (parent instanceof ViewGroup) {
            // Apply a theme wrapper, if requested. This is sort of a weird
            // edge case, since developers think the <include> overwrites
            // values in the AttributeSet of the included View. So, if the
            // included View has a theme attribute, we'll need to ignore it.
            
            //private static final int[] ATTRS_THEME = new int[] {
            com.android.internal.R.attr.theme };

            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
            final int themeResId = ta.getResourceId(0, 0);
            final boolean hasThemeOverride = themeResId != 0;
            if (hasThemeOverride) {
                context = new ContextThemeWrapper(context, themeResId);
            }
            ta.recycle();

            // If the layout is pointing to a theme attribute, we have to
            // massage the value to get a resource identifier out of it.
            int layout = attrs.getAttributeResourceValue(null, ATTR_LAYOUT, 0);
            if (layout == 0) {
                final String value = attrs.getAttributeValue(null, ATTR_LAYOUT);
                if (value == null || value.length() <= 0) {
                    throw new InflateException("You must specify a layout in the"
                            + " include tag: <include layout=\"@layout/layoutID\" />");
                }

                // Attempt to resolve the "?attr/name" string to an attribute
                // within the default (e.g. application) package.
                layout = context.getResources().getIdentifier(
                        value.substring(1), "attr", context.getPackageName());

            }

            // The layout might be referencing a theme attribute.
            if (mTempValue == null) {
                mTempValue = new TypedValue();
            }
            if (layout != 0 && context.getTheme().resolveAttribute(layout, mTempValue, true)) {
                layout = mTempValue.resourceId;
            }

            if (layout == 0) {
                final String value = attrs.getAttributeValue(null, ATTR_LAYOUT);
                throw new InflateException("You must specify a valid layout "
                        + "reference. The layout ID " + value + " is not valid.");
            } else {
                final XmlResourceParser childParser = context.getResources().getLayout(layout);

                try {
                    final AttributeSet childAttrs = Xml.asAttributeSet(childParser);

                    while ((type = childParser.next()) != XmlPullParser.START_TAG &&
                            type != XmlPullParser.END_DOCUMENT) {
                        // Empty.
                    }

                    if (type != XmlPullParser.START_TAG) {
                        throw new InflateException(childParser.getPositionDescription() +
                                ": No start tag found!");
                    }

                    final String childName = childParser.getName();

                    if (TAG_MERGE.equals(childName)) {
                        // The <merge> tag doesn't support android:theme, so
                        // nothing special to do here.
                        rInflate(childParser, parent, context, childAttrs, false);
                    } else {
                        final View view = createViewFromTag(parent, childName,
                                context, childAttrs, hasThemeOverride);
                        final ViewGroup group = (ViewGroup) parent;

                        final TypedArray a = context.obtainStyledAttributes(
                                attrs, R.styleable.Include);
                        final int id = a.getResourceId(R.styleable.Include_id, View.NO_ID);
                        final int visibility = a.getInt(R.styleable.Include_visibility, -1);
                        a.recycle();

                        // We try to load the layout params set in the <include /> tag.
                        // If the parent can't generate layout params (ex. missing width
                        // or height for the framework ViewGroups, though this is not
                        // necessarily true of all ViewGroups) then we expect it to throw
                        // a runtime exception.
                        // We catch this exception and set localParams accordingly: true
                        // means we successfully loaded layout params from the <include>
                        // tag, false means we need to rely on the included layout params.
                        ViewGroup.LayoutParams params = null;
                        try {
                            params = group.generateLayoutParams(attrs);
                        } catch (RuntimeException e) {
                            // Ignore, just fail over to child attrs.
                        }
                        if (params == null) {
                            params = group.generateLayoutParams(childAttrs);
                        }
                        view.setLayoutParams(params);

                        // Inflate all children.
                        rInflateChildren(childParser, view, childAttrs, true);

                        if (id != View.NO_ID) {
                            view.setId(id);
                        }

                        switch (visibility) {
                            case 0:
                                view.setVisibility(View.VISIBLE);
                                break;
                            case 1:
                                view.setVisibility(View.INVISIBLE);
                                break;
                            case 2:
                                view.setVisibility(View.GONE);
                                break;
                        }

                        group.addView(view);
                    }
                } finally {
                    childParser.close();
                }
            }
        } else {
            throw new InflateException("<include /> can only be used inside of a ViewGroup");
        }

        LayoutInflater.consumeChildElements(parser);
    }

这个方法跟上面的inflate()方法很相似,具体逻辑就不看了,主要也是调用了createViewFromTag()方法来创建View,这就是上面为什么说include标签也会创建view的原因,至此我们已经知道了createViewFromTag方法用于创建View。

其他View标签

上面我们看完了inflate里的merge标签实现,现在继续看看后面的实现:

    ···
     // Temp is the root view that was found in the xml
    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

    ViewGroup.LayoutParams params = null;

    if (root != null) {
         ···
        // Create layout params that match root, if supplied
        params = root.generateLayoutParams(attrs);
        if (!attachToRoot) {
            // Set the layout params for temp if we are not
            // attaching. (If we are, we use addView, below)
            temp.setLayoutParams(params);
            }
        }
        ···
        // Inflate all children under temp against its context.
        rInflateChildren(parser, temp, attrs, true);
        ···
        // We are supposed to attach all the views we found (int temp)
        // to root. Do that now.
        if (root != null && attachToRoot) {
            root.addView(temp, params);
        }

        // Decide whether to return the root that was passed in or the
        // top view found in xml.
        if (root == null || !attachToRoot) {
            result = temp;
        }
    ···

首先这里还是调用了createViewFromTag方法用于创建view,然后当根View不为空时,则加载根View的LayoutParams属性,然后如果attachToRoot为false,则调用setLayoutParams为创建的View设置属性,如果为true则直接调用addView方法添加到根View中。然后会调用rInflateChildren方法来实现子view的创建与添加。最后如果根View不为空并且attachToRoot为true,则返回根View,否则返回的是创建的xml根标签指定的View。

createViewFromTag创建View

现在知道了createViewFromTag用于创建View,那么现在需要了解一下它的实现细节:

private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
        return createViewFromTag(parent, name, context, attrs, false);
    }

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        ···

        try {
            View view;
            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);
            }
            
            //注释1
            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    if (-1 == name.indexOf('.')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
        } 
        ···
}

这里首先会使用mFactory2,mFactory,mPrivateFactory这三个对象按先后顺序创建view,但那如果这三个对象都为空的话,则会默认流程来创建View,最后返回View。通常来讲这三个Factory都为空,如果我们想要控制View的创建过程就可以利用这一机制来定制自己的factory。现在我们先来分析一下注释1的代码:

if (view == null) {
    final Object lastContext = mConstructorArgs[0];
    mConstructorArgs[0] = context;
    try {
        //String的indexOf()方法如果没有找到给定的字符则返回-1
        if (-1 == name.indexOf('.')) {
            view = onCreateView(parent, name, attrs);
        } else {
            view = createView(name, null, attrs);
        }
    } finally {
        mConstructorArgs[0] = lastContext;
    }
}

首先会判断名字中是否含有点,这主要是为了区分系统自带View和自定义View。因为系统View是直接使用类名不用写全包名的,而自定义View在使用的时候一定要写全包名,相信大家可以很容易的理解到这一点,然后如果是自定义View则调用createView来创建View,否则调用onCreateView方法。

public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class<? extends View> 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);
                    }
                }
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
            } else {
                ···
            }

            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;

            //注释1
            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 (NoSuchMethodException e) {
            ···
        } finally {
            ···
        }
    }

LayoutInflater内部维护了一个Map用于缓存构造器,然后在这里首先会从这个map中获取构造器否则创建后再放至map中;当获取了构造器之后,在注释1处通过反射创建了View。然后我们再看创建系统View:

在LayoutInflater中我们找到了对应的方法:

protected View onCreateView(View parent, String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return onCreateView(name, attrs);
    }
protected View onCreateView(String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return createView(name, "android.view.", attrs);
    }

原来在LayoutInflater的onCreateView方法创建系统View最终的实现也是交给了createView方法,只是传入了一个字符串android.view.,这样在创建构造器时就会与View的名字拼接到一起获取对应的Class对象,使最终能够成功创建对应的View。现在到PhoneLayoutInflater里找一下这个方法:

private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };

/** Override onCreateView to instantiate names that correspond to the
        widgets known to the Widget factory. If we don't find a match,
        call through to our super class.
    */
    @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) {
                // In this case we want to let the base class take a crack
                // at it.
            }
        }

        return super.onCreateView(name, attrs);
    }

主要完成的是遍历一个存放了三个包名字符串的数组,然后调用createView方法创建View,只要这三次创建View有一次成功,那么就返回创建的View,否则最终返回的还是父类传入"android.view."时创建的View。现在再看看createView的具体实现:

   public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
            //从缓存器中获取构造器
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class<? extends View> 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
                //通过传入的prefix构造出完整的类名 并加载该类
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);

                //省略部分代码
                
                //从class对象中获取构造器
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                //存入缓存器中
                sConstructorMap.put(name, constructor);
            } else {
                //代码省略
            }

           //代码省略
          
            //通过反射创建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;

        } 
        //省略各种try catch代码
    }

这里就创建了View对象,结合之前调用的rInflate方法构建整个View树,整个View树上的对象就全部被创建出来了,最后就会被调用显示在我们的视野中。

上一篇下一篇

猜你喜欢

热点阅读