LayoutInflater简单理解

在LayoutInflater的学习中有以下体会:

先看几个例子

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout);

        // Example1 出错
        //View trueLayout = LayoutInflater.from(this).inflate(R.layout.button_layout, mainLayout, true);
        //mainLayout.addView(trueLayout);

        // Example2 Button的Params无效
        //View trueLayout = LayoutInflater.from(this).inflate(R.layout.button_layout,null);
        //mainLayout.addView(trueLayout);

        // Example3
        LayoutInflater.from(this).inflate(R.layout.button_layout, mainLayout, true);

        // Example4
        View falseLayout = LayoutInflater.from(this).inflate(R.layout.button_layout, mainLayout, false);
        mainLayout.addView(falseLayout);
    }

布局文件如下:
activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal">
    </LinearLayout>

button_layout.xml

    <Button xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="100dp" android:layout_height="wrap_content" android:text="Button">
    </Button>

Example1:
会抛出异常
Example2:
Button的宽度没有100dp只是WRAP_CONTNET
Example3:
正常
Example4:正常

原因:
首先进入LayoutInflater#inflate()源码看看:

    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(parser, root, attachToRoot);

    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
                }

                //找到xml文档的Start位置
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }

                final String name = parser.getName();

                if (DEBUG) {
                    System.out.println("**************************");
                    System.out.println("Creating root view: "
                            + name);
                    System.out.println("**************************");
                }

                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 {
                    //重点1:Temp节点是要解析的xml文档的root节点
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    //重点2:parms到底是temp节点还是root的LayoutParams
                    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
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            // 重点3:当attachToRoot == false 时,调用下面函数
                            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) {
                        // 重点4:当attachToRoot == true时,调用下面函数
                        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) {
                InflateException ex = new InflateException(e.getMessage());
                ex.initCause(e);
                throw ex;
            } catch (Exception e) {
                InflateException ex = new InflateException(
                        parser.getPositionDescription()
                                + ": " + e.getMessage());
                ex.initCause(e);
                throw ex;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;
            }

            Trace.traceEnd(Trace.TRACE_TAG_VIEW);

            return result;
        }
    }
  • 解析xml文档采用的PULL方式
  • 区分roottemproot为函数参数ViewGroup,temp为xml文档的根节点
  • attachToRoot == true会调用root.addView(temp, params);,所以在一开始的Example1就会出错(不能重复添加啊),Example3就对了。当attachToRoot == fasle调用temp.setLayoutParams(params);所以在Example4要调用mainLayout.addView(falseLayout);不然就看不到Button了。
  • 对于params变量(我一开始想了好久),params = root.generateLayoutParams(attrs);这句代码
    /** * Returns a new set of layout parameters based on the supplied attributes set. * * @param attrs the attributes to build the layout parameters from * * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one * of its descendants */
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }

返回一个LayoutParams基于给的AttributeSet参数,那么AttributeSet从哪里来?

final AttributeSet attrs = Xml.asAttributeSet(parser);

parser为xml文档的parser,所以params变量为temp的LayoutParams(xml文档里面设置啦)。
- 当attachToRoot == trueinflate()函数返回root;当attachToRoot == trueinflate()函数返回temp

最后说一点:

  1. layout_heightlayout_width不是View的真实高度,它是根据Parent View与当前View决定的。
  2. Example2,里面由于root为空,默认attachToRoottrueparams = root.generateLayoutParams(attrs);就不会调用,params就为空。还有一点就是:root.addView(temp, params);不会调用。

你可能感兴趣的:(android,inflater)