Android LayoutInflater加载.xml文件原理分析

Android LayoutInflater 的原理分析

以下文章是在拜读guolin大神的文章后,自己进行的一个总结。
原文: http://blog.csdn.net/guolin_blog/article/details/12921889

接触Android的朋友,都知道使用LayoutInflater可以将布局加载到当前的上下文中,通常,我们加载布局的任务都是在Activity 中调用setContentView()来完成的,其实setContentView()中也是使用LayoutInflater来加载布局的。接下来,我们就剖析一下LayoutInflater的工作流程。

LayoutInflater的基本用法,首先需要获取到LayoutInflater对象:

 LayoutInflater layoutInflater = LayoutInflater.from(context);

也有另外的一种写法:

LayoutInflater  layoutInflater = (LayoutInflater)      
           context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

得到LayoutInflater的实例后,就可以调用inflate()方法来加载布局,如下所示:

layoutInflater.inflate(resourceId,root);

inflate()方法一般接收两个参数,第一个就是要加载的布局id,第二个就是給该布局外部再嵌套一层父布局,如果不需要就直接传入null.

用小例子来说明一下LayoutInflater的用法.
比如说当前有一个项目,其中MainActivity中的布局叫做activity_main.xml,现在的版本不能只有LinearLayout,所以我们添加一个控件TextView,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.aofei.myview.MainActivity">
    <TextView
        android:text="Inflter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

然后,我们再定义一个布局文件button_layout.xml,里面只有一个Button控件

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   android:text="Button">
</Button>

现在我们要想办法,如何通过LayoutInflater来将button_layout布局加载到LinearLayout中,使用两种创建LayoutInflater对象加载方法都可以将实现。MainActivity中的代码如下:

public class MainActivity extends AppCompatActivity {
   private LinearLayout linearLayout ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        linearLayout= (LinearLayout) findViewById(R.id.main_layout);
        LayoutInflater inflater = LayoutInflater.from(this);
       View view= inflater.inflate(R.layout.button_layout,null);
        linearLayout.addView(view);

    }
}

从代码中可以看到,我们先是获取来LayoutInflater的实例,然后调用它的inflate()方法来加载button_layout这个布局,最后调用LinarLayout的addView()方法将它添加到LinearLayout中,效果如下图:

这里写图片描述

Button在界面上显示出来了!说明我们确实是借助LayoutInflater将button_layout.xml这个布局添加到了LinearLayout中了。LayoutInflater广泛应用于需要动态添加View的时候,比如在ScrollView和ListView中,经常可以看到LayoutInflater的身影。

仅仅是了解了如何使用LayoutInflater显然对于一个专业的Android开发工程师是不够的,我们需要知道到底LayoutInflater是如何工作的。
我们查看View view= inflater.inflate(R.layout.button_layout,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()方法重载,最终都会辗转调用到LayoutInflater的如下代码中:

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {  
    synchronized (mConstructorArgs) {  
        final AttributeSet attrs = Xml.asAttributeSet(parser);  
        mConstructorArgs[0] = mContext;  
        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 (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, attrs);  
            } else {  
                View temp = createViewFromTag(name, attrs);  
                ViewGroup.LayoutParams params = null;  
                if (root != null) {  
                    params = root.generateLayoutParams(attrs);  
                    if (!attachToRoot) {  
                        temp.setLayoutParams(params);  
                    }  
                }  
                rInflate(parser, temp, attrs);  
                if (root != null && attachToRoot) {  
                    root.addView(temp, params);  
                }  
                if (root == null || !attachToRoot) {  
                    result = temp;  
                }  
            }  
        } catch (XmlPullParserException e) {  
            InflateException ex = new InflateException(e.getMessage());  
            ex.initCause(e);  
            throw ex;  
        } catch (IOException e) {  
            InflateException ex = new InflateException(  
                    parser.getPositionDescription()  
                    + ": " + e.getMessage());  
            ex.initCause(e);  
            throw ex;  
        }  
        return result;  
    }  
}  

从上面的代码中我们可以清晰的看出,LayoutInflater其实就是使用Android提供的pull解析方法来解析布局文件的,不熟悉pull可以网上查看一下相关的文章,注意代码中的View temp = createViewFromTag(name, attrs); 这个方法,把节点和参数传递了进去,根据节点名来创建View对象。确实如此,在createViewFromTag()方法内部又会去调用createView()方法,然后使用反射的方式创建出View的实例并返回。

当然,这里只是创建出了一个根布局的实例而已,接下来会在第31行调用rInflate()方法来循环遍历这个跟布局下的子元素,代码如下所示:

private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs)  
        throws XmlPullParserException, IOException {  
    final int depth = parser.getDepth();  
    int type;  
    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)) {  
            parseRequestFocus(parser, parent);  
        } else if (TAG_INCLUDE.equals(name)) {  
            if (parser.getDepth() == 0) {  
                throw new InflateException("<include /> cannot be the root element");  
            }  
            parseInclude(parser, parent, attrs);  
        } else if (TAG_MERGE.equals(name)) {  
            throw new InflateException("<merge /> must be the root element");  
        } else {  
            final View view = createViewFromTag(name, attrs);  
            final ViewGroup viewGroup = (ViewGroup) parent;  
            final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);  
            rInflate(parser, view, attrs);  
            viewGroup.addView(view, params);  
        }  
    }  
    parent.onFinishInflate();  
}  

在该方法中同样是createViewFromTag()方法来创建View的实例,然后还会在第24行递归调用rInflate()方法来查找这个View下的子元素,每次递归完成后则将这个View添加到父布局当中。

这样的话,把整个布局文件都解析完成后,就形成一个完整的DOM结构,最终会把最顶层的根布局返回,至此inflate()过程全部结束。

大家也会注意到,inflate()方法还有个接收三个参数的方法重载,结构如下:

inflate(int resource,ViewGroup root,boolean attachToRoot)

那么这三个参数attachToRoot又是什么意思呢?其实如果你仔细去阅读上面的源码应该可以自己分析出答案:
1.如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
2。如果root不为null,attachToRoot设为true,则会給加载的布局文件指定一个父布局,即root。
3.如果root 不为null,attachToRoot 设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。
4.在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true.

现在对LayoutInflater的工作原理和流程也搞清楚了,你该满足了吧,呃。。。那么我们想給遍这个例子中的Button大小,想要调大一些,那简单的呀,修改button_lauyout.xml 中的代码,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:text="Button
  ">

</Button>

运行后发现没有变化,还是原来的大小,这是为神马呢?其实不管我们将button_layout.xml中Button 的大小改为多少,都不会有效果,因为这两个值已经完全失去了作用。

平时我们经常使用layout_width和layout_height来设置View的大小,并且一直都能正常工作,就好像这两个属性确实是用于设置View的大小的,而实际上则不然,它们实际上是设置View在布局中的大小,也就是说,首先View必须存在于一个布局中,之后如果layout_width设置成match_parent表示让View的宽度填充布局,如果设置成wrap_content表示让View的宽度刚好可以包含其内容,如果设置成具体的数值则,View的宽度会变成相应的数值。这也是为社么这两个属性叫做layout_width和layout_height,而不是width和height.

再来看下我们的button_layout.xml吧,很明显Button这个控件目前尚不存在于任何布局中,所以layout_width和layout_height这两个属性理所当然没有任何作用,那么怎么修改才能让按钮的大小改变呢?解决方法其实有很多种,最简单的方式就是在Button的外面再嵌套一层布局,如下所示:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:text="Button">
    </Button>
</LinearLayout>

运行后结果如下:

这里写图片描述

这时,我们可以看到,Button的大小发生了变化!

看到这里,也许有些朋友的心中会有一个巨大的疑惑,不对呀!平时在Activity中指定布局文件的时候,最外层的那个布局是可以指定大小的呀!layout_width和layout_height都是有作用的。确实,这主要是因为,在setContentView()方法中,Android会自动在外层再嵌套一个FrameLayout,所以layout _width和layout_height属性才会有效果,那么我们来证实一下吧!修改MainActivity中国年的代码如下所示:

public class MainActivity extends AppCompatActivity {
    private LinearLayout linearLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        linearLayout = (LinearLayout) findViewById(R.id.main_layout);
        ViewParent viewParent= linearLayout.getParent();
        Log.e("xiaokai","the parent of mainLayout is "+viewParent);
    }
}

运行后的结果如下:

这里写图片描述

打印的内容为:

03-07 11:59:00.758 27907-27907/com.aofei.myview E/xiaokai: the parent of mainLayout is android.support.v7.widget.ContentFrameLayout{e8eda2a V.E...... ......I. 0,0-0,0 #1020002 android:id/content}

说到这里,虽然setContentView()方法大家都会用,但实际上Android界面显示的原理要比我们所看到的东西复杂的多,任何一个Activity中显示的界面其实都要由两个部门组成,标题栏和内容布局。标题栏就是在很多界面顶部显示的那部分内容,比如刚刚我们的那个例子当中就有标题栏,可以在代码中控制让它是否显示。而内容布局就是一个FrameLayout,这个布局就是一个FrameLayout,这个布局的id叫做content,我们调用setContentView()方法所传入的布局其实就是放到这个FrameLayout中的,这也是为什么这个方法叫做setContentView() , 而不是叫setView().
最后再附上一张Activity窗口的组成图

这里写图片描述

好了,第一篇关于View的总结,就写到这里了!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java.lang.IllegalStateException: ScrollView can host only one direct child at androidx.core.widget.NestedScrollView.addView(NestedScrollView.java:507) at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1131) at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72) at android.view.LayoutInflater.rInflate(LayoutInflater.java:1101) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088) at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1130) at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72) at android.view.LayoutInflater.rInflate(LayoutInflater.java:1101) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088) at android.view.LayoutInflater.inflate(LayoutInflater.java:686) at android.view.LayoutInflater.inflate(LayoutInflater.java:505) at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:360) at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:443) at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:121) at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:722) at com.android.tools.idea.rendering.RenderTask.lambda$inflate$9(RenderTask.java:879) at com.android.tools.idea.rendering.RenderExecutor$runAsyncActionWithTimeout$3.run(RenderExecutor.kt:194) at com.android.tools.idea.rendering.RenderExecutor$PriorityRunnable.run(RenderExecutor.kt:292) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:829)
06-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值