美文网首页view绘制
setContentView与LayoutInflater详解

setContentView与LayoutInflater详解

作者: 留给时光吧 | 来源:发表于2018-05-14 21:30 被阅读0次

一个应用最基本的就是一个个的Activity,在Activity入口方法onCreate中的第一步就是setContentView也就是加载布局文件。今天我们就来学习一下Android中加载布局文件的流程。

通过本文你也许能明白下面几个问题:

  • 1.setContentView(id)真正的机制与原理
  • 2.marge为什么不增加视图层数以及为什么不能用于根布局但必须用于xml文件的根标签
  • 3.自定义view在写到xml文件中时为什么会调用两参数的构造方法
  • 4.inflate(resource, root, attachToRoot)三个参数之间的真正关系及一些常见问题
  • 5.ViewStub的几个问题:①.为什么可以提高性能 ②.是如何延迟加载布局的 ③.为什么inflate()只能调用一次而setVisibility(View.VISIBLE)可以多次调用

首先要清楚一点,Activity的类型有很多,有些Activity的setContentView方法和最原始的android.app.Activity中的还是有一定区别的,这里我们以最原始的为依据开始分析,本文源码基于Android 8.0,源码位置

android\frameworks\base\core\java\android\app\Activity.java

setContentView有几个重载方法,但是功能都一样,只不过有的需要传入资源名有的直接传一个view,既然是分析加载xml文件的流程,我们当然看最常用的那个传入资源名的方法:

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

发现实际上是调用的getWindow()的setContentView,先看getWindow():

    public Window getWindow() {
        return mWindow;
    }

    mWindow = new PhoneWindow(this, window, activityConfigCallback);

mWindow是一个PhoneWindow对象,PhoneWindow源码位置:

frameworks\base\core\java\com\android\internal\policy\PhoneWindow.java

我们先不管那个构造函数,直接看setContentView方法

    @Override
    public void setContentView(int layoutResID) {
        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 {
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

这里对有过场动画的情况下做了特殊处理,我们先看没有过程动画的情况。到这里我们发现最后调用了inflate方法,和我们在做listview等一些场景中加载一个布局文件的方法是一样的。接下来就着重看看这里。

先看mLayoutInflater的实例化过程:

android\frameworks\base\core\java\android\view\LayoutInflater.java

    mLayoutInflater = LayoutInflater.from(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 只是一个抽象类,getSystemService必定是它的一个实现类中的,就是ContextImpl(至于这里面的关系,详见此处),ContextImpl源码位置:

android\frameworks\base\core\java\android\app\ContextImpl.java
    @Override
    public Object getSystemService(String name) {
        return SystemServiceRegistry.getSystemService(this, name);
    }

再看 SystemServiceRegistry.getSystemService,SystemServiceRegistry也在app包下

    public static Object getSystemService(ContextImpl ctx, String name) {
        ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
        return fetcher != null ? fetcher.getService(ctx) : null;
    }

    private static final HashMap<String, ServiceFetcher<?>> SYSTEM_SERVICE_FETCHERS =
            new HashMap<String, ServiceFetcher<?>>();

发现SYSTEM_SERVICE_FETCHERS 只是一个HashMap,getSystemService所做的操作仅仅是按名字去内容,那么我们就看看这个HashMap的put方法,看有没有什么收获。经过搜索,这个类中有个registerService方法用来put:

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

这里要清楚,有可能是外部某个类调用这个方法用来注册服务,这时候我们只能全文搜索注册LayoutInflater时用的key--Context.LAYOUT_INFLATER_SERVICE。幸运的时,这个服务就是在SystemServiceRegistry的static代码段中注册的:

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

跟踪了一圈终于找到了,LayoutInflater的具体实现类就是PhoneLayoutInflater。PhoneLayoutInflater代码位置:

android\frameworks\base\core\java\com\android\internal\policy\PhoneLayoutInflater.java

这个类中,我们当然要先看一下inflate的实现,但是并没有找到。原来PhoneLayoutInflater并没有重写inflate方法,调用的还是抽象类LayoutInflater内原本就实现的。。。既然如此,还是看一下吧:

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

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

上面这个过程主要工作就是构造了一个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 {
                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!");
                }

                final String name = parser.getName();

                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 {
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }

                    rInflateChildren(parser, temp, attrs, true);

                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
                final InflateException ie = new InflateException(e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } catch (Exception e) {
                final InflateException ie = new InflateException(parser.getPositionDescription()
                        + ": " + e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } finally {
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;

                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            return result;
        }
    }

这个方法还是比较长的,我们一点一点看。从try代码段开始。第一个while循环是寻找开始标签或结束标签。如果直接先找到结束标签,则抛异常。否则区除标签名。

之后如果是marge标签,则root不能为空且attachToRoot不能为false。这里也就验证了marge使用时不能作为根布局。对于marge的处理是调用了rInflate方法:

    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)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } 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标签则抛异常,若为include标签,执行parseInclude方法,由于include主要是引入另一个xml文件,所以parseInclude功能和inflate类似,这里先不介绍。在if判断的最后一块则是重点,这里是创建view的真正地方,调用了createViewFromTag方法,然后配置LayoutParams ,最后添加到viewGroup中,这也就是marge为什么不添加嵌套等级的原因。上面两个方法我们放到后面讲。

到这里marge标签处理完了,我们在回到inflate方法,看不是marge标签的情况。既然不是marge标签则就是一个view了,所以直接调用了:

final View temp = createViewFromTag(root, name, inflaterContext, attrs);

这里我们就来看一下这个核心的方法:

    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) {
        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;
            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 = onCreateView(parent, name, attrs);
                    } else {
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
        } 
        .....
    }

首先调用了另一个重载方法,并将参数ignoreThemeAttr改为false,意思是会收到主题的影响。接下来首先处理了一下如果标签是blink的情况,这种东西好像很少用,有兴趣的可以去查找一下。我们看正常情况:

首先出现了mFactory2、mFactory 和mPrivateFactory三个变量。我们先探究一下这三个参数的来历,首先看一下他们的类:

public interface Factory {
      public View onCreateView(String name, Context context, AttributeSet attrs);
}

public interface Factory2 extends Factory {
      public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
}

全都是接口,再看他们初始化的地方,首先是在构造中:

    protected LayoutInflater(LayoutInflater original, Context newContext) {
        mContext = newContext;
        mFactory = original.mFactory;
        mFactory2 = original.mFactory2;
        mPrivateFactory = original.mPrivateFactory;
        setFilter(original.mFilter);
    }

不过回顾LayoutInflater的创建过程:

LayoutInflater.from(context) -> 
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ->
new PhoneLayoutInflater(ctx.getOuterContext()); -> 
LayoutInflater(context)

而这三个参数是在LayoutInflater的另外一个两参数构造中初始化的,所以从Activity中过来时,这三个参数都为空。

但是他们还有set方法:

void setFactory(Factory factory) 
void setFactory2(Factory2 factory)
void setPrivateFactory(Factory2 factory)

通过搜索在Activity中调用了setPrivateFactory:

final void attach(....) {
        ...
        mWindow.getLayoutInflater().setPrivateFactory(this);
        ...
}

传入的是this,是因为Activity实现了Factory2 接口:

    @Nullable
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return null;
    }
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        if (!"fragment".equals(name)) {
            return onCreateView(name, context, attrs);
        }

        return mFragments.onCreateView(parent, name, context, attrs);
    }

从代码中看,主要是对标签为fragment时做了处理,由于我们主要是看layout的加载,当标签不为fragment时返回null,所以我们直接从createViewFromTag中的view==null开始看。

接下来又出现一个if判断,主要是判断标签中是否有“.”,有则代表是自定义view,没有则是系统内置的。分别调用不同的方法。对于自定义view:

    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) {
                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 {
                if (mFilter != null) {
                    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) {
                mConstructorArgs[0] = mContext;
            }
            Object[] args = mConstructorArgs;
            args[1] = attrs;

            final View view = constructor.newInstance(args);
            if (view instanceof ViewStub) {
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            mConstructorArgs[0] = lastContext;
            return view;

        } 
        ....
    }

关键代码是这一句·:

constructor = clazz.getConstructor(mConstructorSignature);

static final Class<?>[] mConstructorSignature = new Class[] {Context.class, AttributeSet.class};

看见是利用了反射,并且调用了view众多构造中的两参数那个,这也就验证了为什么在xml文件中,自定义view会调用两参数的构造。获得了构造后他还会存起来供下次使用,节省性能。之后便调用了newInstance方法,并传入了context和attrs。接下来又处理了view时是ViewStub的情况。如果是ViewStub则给他设置一个LayoutInflater,这里的cloneInContext实现在PhoneLayoutInflater中:

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

可见就是给他一个LayoutInflater以便于在ViewStub调用inflate()时使用,ViewStub的inflate()方法实际上就是调用了LayoutInflater的inflate方法来加载view,这样就实现了界面加载效率的提高(具体分析见文章最后)。

看完自定义view的加载,我们再看内置view的加载,调用的时onCreateView方法:

    protected View onCreateView(View parent, String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return onCreateView(name, attrs);
    }

这里的两参数onCreateView方法在PhoneLayoutInflater中有重写:

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

sClassPrefixList值为下:

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

最后也调用了createView方法,和自定义view的一样,只不过自定义view中createView第二个参数为null,内置view这里有值,主要是讲TextView,ImageView这些简称补全为全类名,方便反射。

到这里一个view基本上是创建出来了,我们再回溯到inflate方法中(代码跨度比较大,源码分析就是这样,但我们心中要有清晰的线路),在创建完view后,做了一个root != null的判断,这里是读取了根布局的Params,只有attachToRoot为false时,才会应用父节点的布局参数,这也就是我们在使用ListView或者RecycleView创建View时,为什么有时候根标签的属性会补齐作用的原因,到这里下面这个我们常用方法的三个参数的意义应该都清楚了:

View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

在配置完参数后,又调用了rInflateChildren去解析标签内的子view:

    final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws XmlPullParserException, IOException {
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

这个里面又调用了rInflate方法,基本上就是深度优先的遍历解析xml文件,把遇到的所有标签换为对应对象,然后viewGroup.addView方法一层一层联系起来。

在inflate方法最后,通过两个判断,确定是返回根布局还是单个view。我们从Activity中过来时,root不为空,attachToRoot为true,根据流程时将解析出来的view添加到根布局并返回根布局。再介绍另外一个场景,就是在Listview中getView时,我们参考一个权威的写法:

view = inflater.inflate(resource, parent, false);

上面来自于ArrayAdapter。他的attachToRoot为false,所以返回的是我们要构建的xml文件内容,也就是一个一个item中要显示的内容。

最后的最后,我们在回到PhoneWindow的setContentView方法,这里只是简单的调用mLayoutInflater.inflate(layoutResID, mContentParent);,根据上一段的流程分析,目的就是将xml文件解析出来的视图树添加到mContentParent(关于mContentParent的具体可以分析PhoneWindow的内容,这里就不详细说明了,只用知道他是DecorView的一部分,是Activity的视图区域即可)。

到这里我们的分析基本上就完成了,我们最后梳理一下,前一部分跟踪了setContentView的调用,发现最后调用了mLayoutInflater.inflate(layoutResID, mContentParent);方法。inflate方法只是一个入口,具体一层一层解析xml文件视图树的任务则交给了rInflate方法,根据标签创建view对象的任务交给了createViewFromTag方法,遍历的方法是深度优先遍历的。

最后我们在处理一个遗留问题,就是关于ViewStub的,都说使用这个会节省内存提高性能,到底因为什么呢,我们借这个分析LayoutInflater.inflate的机会来看一下。

第一个问题:我们说ViewStub中的内容是不会立即创建出对象的,而其他view不管是不是GONE状态都会创建。这点很好证明,在createView方法中,我们并没有看到任何地方会根据VIew的可见性来控制对象的创建,而单独对ViewStub做了特殊处理,仅仅实例化了ViewStub对象,而对其内部的layout没有处理,所以可以说明ViewStub确实有延迟加载的功能,可以在界面创建阶段不过多的加载view节省内存。

第二个问题:我们都说ViewStub被设置为可见的时候,或是调用了ViewStub.inflate()的时候,布局才会被加载,到底是不是呢?我们看ViewStub的源码:

android\frameworks\base\core\java\android\view\ViewStub.java
    public void setVisibility(int visibility) {
        if (mInflatedViewRef != null) {
            View view = mInflatedViewRef.get();
            if (view != null) {
                view.setVisibility(visibility);
            } else {
                throw new IllegalStateException("setVisibility called on un-referenced view");
            }
        } else {
            super.setVisibility(visibility);
            if (visibility == VISIBLE || visibility == INVISIBLE) {
                inflate();
            }
        }
    }

    public View inflate() {
        final ViewParent viewParent = getParent();

        if (viewParent != null && viewParent instanceof ViewGroup) {
            if (mLayoutResource != 0) {
                final ViewGroup parent = (ViewGroup) viewParent;
                final View view = inflateViewNoAdd(parent);
                replaceSelfWithView(view, parent);

                mInflatedViewRef = new WeakReference<>(view);
                if (mInflateListener != null) {
                    mInflateListener.onInflate(this, view);
                }

                return view;
            } else {
                throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
            }
        } else {
            throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
        }
    }

    private View inflateViewNoAdd(ViewGroup parent) {
        final LayoutInflater factory;
        if (mInflater != null) {
            factory = mInflater;
        } else {
            factory = LayoutInflater.from(mContext);
        }
        final View view = factory.inflate(mLayoutResource, parent, false);

        if (mInflatedId != NO_ID) {
            view.setId(mInflatedId);
        }
        return view;
    }

可见调用setVisibility设置为VISIBLE 或INVISIBLE是就会调用inflate()。而inflate()中的inflateViewNoAdd方法就是调用了LayoutInflater的inflate方法去解析布局文件(这里的LayoutInflater实例就是在LayoutInflater的createView中最后若一个view是ViewStub时调用setLayoutInflater传入的),最后在ViewStub的inflate()中调用replaceSelfWithView将布局中ViewStub自己替换为inflate出来的视图树,replaceSelfWithView也很简单就是移除和添加:

    private void replaceSelfWithView(View view, ViewGroup parent) {
        final int index = parent.indexOfChild(this);
        parent.removeViewInLayout(this);

        final ViewGroup.LayoutParams layoutParams = getLayoutParams();
        if (layoutParams != null) {
            parent.addView(view, index, layoutParams);
        } else {
            parent.addView(view, index);
        }
    }

第三个问题,为什么inflate()只能用一次而setVisibility(View.VISIBLE )可以多次调用?这个在上面方法中就能发现,它直接把ViewStub移除,新的布局被替换进去,这也就是为什么Inflate只能调用一次的原因,因为在inflate()中viewParent 为空,将抛异常。另外在inflate()中实例化了mInflatedViewRef 对象,下次调用setVisibility时,由于mInflatedViewRef 不为空,就调用不到inflate()了,所以可以安全的多次调用setVisibility。

相关文章

网友评论

    本文标题:setContentView与LayoutInflater详解

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