LayoutInflater的inflater引发的问题

LayoutInflater的inflater引发的问题

平常在用LayoutInflater的inflater方法时,一般都是这样写:inflate(R.layout.a,null),第二个参数为啥用null都不明白,直到遇到用fragment中的布局replace一个linearlayout的时候,才真正去了解其中的含义。

场景还原

一、场景还原

这里写图片描述

在Activity中用LinearLayout作为Fragment的占位符,在代码中动态replace。其中LinearLayout的宽高都是match_parent,fragment对应的布局宽高也都是match_parent,其中fragment中生成view的代码如下:

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.content_main,null);
    }

但当运行的时候,fragment宽是match_parent,高却是wrap_content。这就让我摸不着头脑了。

二、问题分析

用hierarchy viewer查看布局嵌套层次,LinearLayout就是fragment的父view,fragment对应的layout作为一个子viewadd到LinearLayout中。LinearLayout是match_parent没有问题,只能是fragment对应的layout在添加时高度的match_parent被改变成wrap_content。再接着分析,此layout就是在onCreateView中return的view。那么就自然地想到这个inflater函数。

这个inflater有两个常用到的重载,分别是:

/**

/**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy.
     * @return The root View of the inflated hierarchy. If root was supplied,
     *         this is the root View; otherwise it is the root of the inflated
     *         XML file.
     */
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }

     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy (if
     *        <em>attachToRoot</em> is true), or else simply an object that
     *        provides a set of LayoutParams values for root of the returned
     *        hierarchy (if <em>attachToRoot</em> is false.)
     * @param attachToRoot Whether the inflated hierarchy should be attached to
     *        the root parameter? If false, root is only used to create the
     *        correct subclass of LayoutParams for the root view in the XML.
     * @return The root View of the inflated hierarchy. If root was supplied and
     *         attachToRoot is true, this is root; otherwise it is the root of
     *         the inflated XML file.
     */
    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();
        }
    }

可以看到第一个也是调用了第二个函数实现的,那么就分析第二个函数,参数root表示父view,attachToRoot表示是否将创建出来的view添加到父view中。最终调用了如下的第三个重载:

/**

     **inflater内部逻辑代码(部分)**

     * Inflate a new view hierarchy from the specified XML node. Throws
     * {@link InflateException} if there is an error.
     * <p>
     * <em><strong>Important</strong></em>&nbsp;&nbsp;&nbsp;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.
     *
     * @param parser XML dom node containing the description of the view
     *        hierarchy.
     * @param root Optional view to be the parent of the generated hierarchy (if
     *        <em>attachToRoot</em> is true), or else simply an object that
     *        provides a set of LayoutParams values for root of the returned
     *        hierarchy (if <em>attachToRoot</em> is false.)
     * @param attachToRoot Whether the inflated hierarchy should be attached to
     *        the root parameter? If false, root is only used to create the
     *        correct subclass of LayoutParams for the root view in the XML.
     * @return The root View of the inflated hierarchy. If root was supplied and
     *         attachToRoot is true, this is root; otherwise it is the root of
     *         the inflated XML file.
     */
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {

        、、、、省略

    // 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) {
            if (DEBUG) {
                System.out.println("Creating params from root: " +
                        root);
            }
            // 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);
           }
        }

        if (DEBUG) {
            System.out.println("-----> start inflating children");
        }

        // Inflate all children under temp against its context.
        rInflateChildren(parser, temp, attrs, true);

        if (DEBUG) {
            System.out.println("-----> done inflating children");
        }

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

        、、、、省略
    }

当root为null时,32行和59行的判断就不会进,最终返回的result就没有parms属性,onCreateView返回的view会被add到LinearLayout中,而LinearLayout里默认的layout属性如下:

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        if (mOrientation == HORIZONTAL) {
            return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        } else if (mOrientation == VERTICAL) {
            return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        }
        return null;
    }

当LinearLayout为竖直排列时,高度就会默认为wrap_content。所以也就出现问题了。

解决过程

既然知道了原因,那么就开始着手修改,首先我将onCreateView修改为如下:

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.content_main,container);
    }

但当运行的时候,会出现崩溃,记录如下:

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4309)
at android.view.ViewGroup.addView(ViewGroup.java:4145)
at android.view.ViewGroup.addView(ViewGroup.java:4086)
at android.view.ViewGroup.addView(ViewGroup.java:4059)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1338)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:388)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:554)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at com.goertek.uitest.MainActivity.onStart(MainActivity.java:41)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
at android.app.Activity.performStart(Activity.java:6253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)

这种错误很奇怪,我又没有多次调用addView添加同一个view,怎么会出现这种报错?
思路断了,只能接着再从inflater的源码中分析了:

这样写inflater,最终是root不为null,attachToRoot为true,分析此时39行运行了addView。
但报错:moveToState(FragmentManager.java:1338),说明是在moveToState中调用了addView而发生的错误,可以考虑是在60行的addView之后,可能是39行的addView已经将view添加了一次,后面系统再添加就会出现错误,为了验证,打log将此过程的分析验证通过:

TestFragment: ----------->onCreateView
10-14 05:59:46.630 10439-10439/? D/AndroidRuntime: Shutting down VM
10-14 05:59:46.630 10439-10439/? E/AndroidRuntime: FATAL EXCEPTION: main

是在执行完onCreateView之后才崩溃的,所以,此时这里就不应该执行60行,那么只能是如下的调用方式:

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.content_main,container,false);

运行之后,问题解决。

当root不为null的时候,32行通过,当attachToRoot为false的时候,temp.setLayoutParams(params)被执行,那么fragment对应布局中的match_parent也就能够实现了。

另外,把LinearLayout替换成FrameLayout,问题也能解决,因为FrameLayout默认的布局就是match_parent

    //framelayout中默认的布局
    /**
     * Returns a set of layout parameters with a width of
     * {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT},
     * and a height of {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}.
     */
    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值