inflater(...)源码解析

以ListView来演示,下面为三种为item的View填充的方法
- view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item, null);
- view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item, new LinearLayout(MainActivity.this), true);
- view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item, new LinearLayout(MainActivity.this), false);

item的布局文件

<Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:orientation="vertical"
        android:text="这里">

</Button>

效果图

效果分别为

  1. 第一种:布局文件最外层设置无效
  2. 第二种:root不为空attachToRoot为true,布局文件最外层设置有效
  3. 第三种:root不为空attachToRoot为false,布局文件最外层设置有效

    源码分析

 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
                }

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

            } 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;
        }
    }
  • 三种情况最终都会来到以上代码块进行最后的处理

参数分析

  1. parser:item的布局文件经过XmlPullParaer之后的
  2. root:inflater中传入的父布局文件
  3. attachToRoot:inflater中传入的boolean类型

关键代码

  • 第9行:初始化result,携带root引用,该属性为最终返回值
  • 第42行:获取item中的最顶层的view,初始化temp并获得引用
  • 第46~58行:若root不为空,则获取temp中的attrs,之后再次判断是否attach to root,若为false,则在此temp.setLayoutParams(attrs),若为true,看注释
  • 第65行:将item中的子view填充进temp中
  • 第73~75行:在root不为空,并且attachToRoot为True的情况下,将temp和attrs添加到root中
  • 第79~81行:在root为空或者attachToRoot为false的情况下,result=temp并且最终返回

分析

  1. 第一种:因为root为空,而attachToRoot为false,所以丢失了item中顶层的attrs属性
  2. 第二种:root不为空,attachToRoot为true,通过root.addView(temp,attrs),所以attrs属性没丢失
  3. 第三种:root不为空,attachToRoot为false,通过temp.setLayoutParams(attrs),所以attrs属性没丢失

注意点

  1. temp.setLayoutParams(attrs):该方法为设置该View在父类中的位置属性,例如layout_width
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值