Android(安卓)LayoutInflater原理解析
最近在看开源项目的时候,发现很多地方用到了
inflate
这个方法,于是乎就想总结一下Android中加载xml布局的方法,然后就有了这篇博客。本博客参考了网上许多大神的博客,会在博客结尾列出,感谢。
一、得到LayoutInflater
想要调用inflate
这个方法,首先需要得到LayoutInflater对象。
先来看看官方给出的解释:
文档说,这个类是用来将一个xml文件实例化成一个与它对应的view对象。需要使用getLayoutInflate()
方法或者getSystemService()
方法来得到一个与当前上下文关联的LayoutInflater实例,这样才能正确地与你App运行的设备匹配。所以,得到LayoutInflater实例的方法有以下几种:
1、getLayoutInflater方法
LayoutInflater inflater = getLayoutInflater();
2、通过getSystemService方法,得到系统服务。
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
3、LayoutInflater的静态方法
LayoutInflater.from(context);
三者其实都是一样的,如果查看源代码的话会发现,其实到最后都是调用了 getSystemService 方法来实现的,也就是使用了上面说的第二种方法,其他几种方法都是对第二种方法的封装,以方便调用。如:
/** * Obtains the LayoutInflater from the given 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;}
二、inflate方法
得到LayoutInflater对象后,我们就可以调用它的inflate
方法来动态加载xml布局文件了。inflate
方法的调用方式有以下几种:
1、使用LayoutInflater对象调用inflate
方法。
LayoutInflater.from(this).inflate(int resource, ViewGroup root);
第一个参数是要加载的布局文件的ID,第二个参数是是否在要加载的布局外面再加一层父布局,如果不需要则传入null即可。第二个参数是否为空还是有一定的区别的,下面我们将会讲到。
2、使用View类的静态方法inflate
直接加载。
/** * Inflate a view from an XML resource. This convenience method wraps the {@link * LayoutInflater} class, which provides a full range of options for view inflation. * * @param context The Context object for your activity or application. * @param resource The resource ID to inflate * @param root A view group that will be the parent. Used to properly inflate the * layout_* parameters. * @see LayoutInflater */public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { LayoutInflater factory = LayoutInflater.from(context); return factory.inflate(resource, root);}
从代码中可以看到,View类静态方法inflate
其实也是对第一种方法的封装。
三、inflate方法参数及返回值解析
如果你翻看源代码,你会发现inflate方法在LayoutInflater类中有4种重载形式。如下:
1、
/** * 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., * R.layout.main_page
) * @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);}
2、
/** * Inflate a new view hierarchy from the specified xml node. Throws * {@link InflateException} if there is an error. * * * Important 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. * @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(XmlPullParser parser, @Nullable ViewGroup root) { return inflate(parser, root, root != null);}
3、
/** * 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., * R.layout.main_page
) * @param root Optional view to be the parent of the generated hierarchy (if * attachToRoot is true), or else simply an object that * provides a set of LayoutParams values for root of the returned * hierarchy (if attachToRoot 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(); }}
4、
/** * Inflate a new view hierarchy from the specified XML node. Throws * {@link InflateException} if there is an error. * * Important 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 * attachToRoot is true), or else simply an object that * provides a set of LayoutParams values for root of the returned * hierarchy (if attachToRoot 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) { 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(" 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、2、3最终都是调用了方法4,而且在方法1、2中,根据第二个参数root是否为空来决定方法4第三个参数attachToRoot是true还是false。如果root为空,那么attachToRoot为false,反之则为true。所以我们一切的疑问都归结到了方法4中。我们来重点看一下,
当我们通过inflate
方法将要加载的布局文件ID传入进来以后,最终会到达方法4,然后在第64行,通过createViewFromTag(root, name, inflaterContext, attrs)
这个方法得到了布局文件对应的view对象。
紧接着,在68行判断传入的root是否为空,如果不为空则通过root为它的子view(也就是刚刚我们生成的布局文件对应的view)生成一个布局参数,params = root.generateLayoutParams(attrs)
,然后在判断attachToRoot是否为true,如果为false则说明不需要将view加入到root中,此时系统只会为刚刚生成的view添加参数,temp.setLayoutParams(params)
。如果attachToRoot为true呢,说明需要将view添加到root中,那么在第95行,系统通过root.addView(temp, params)
方法将view和参数一起添加进了root中。
以上是root不为空的情况,那如果root为空呢?我们可以在第101行看到,当root为空的时候,仅仅是将我们生成的view对象返回而已,并没有加入到root中,也没有为它设置布局参数。没有设置参数会怎样呢?我们下面来看一下。
在这里还需要明确一点,inflate
方法只是将我们指定的布局文件生成view对象,并不负责显示view对象,如果想要显示对象,需要调用setContentView
才可以,或者将view作为子视图加入到已经可以显示的父视图中。当然,我们上面也说到了,如果attachToRoot参数为true的话,系统会帮我们调用addView
将其加入到父视图中。所以如果inflate
方法root为空或者attachToRoot为false,那么我们还需要手动调用addView
方法。
我们首先来看一个例子:
mainActivity中onCreate方法:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RelativeLayout layout = (RelativeLayout) findViewById(R.id.main); View view = LayoutInflater.from(this).inflate(R.layout.button_layout, null); layout.addView(view);}
只是简单地将button_layout布局文件读入并将生成的view加入到主布局中。
button_layout如下:
<?xml version="1.0" encoding="utf-8"?>
然后,运行结果是这样的:
我们在xml中设置的layout_height=”200dp”并没有起作用。这是为什么呢?这就是因为没有设置布局参数导致的。上面的代码中,我直接设置root为空,那么系统将不会为我们生成的view设置布局参数,直接返回view,也就是说,我们在xml中设置的各项参数,系统连管都不管,直接返回一个没有布局参数的view,然后我们使用addView
方法加入到视图中,我们来看一下addView
对于没有布局参数的view是如何处理的:
public void addView(View child, int index) { if (child == null) { throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup"); } LayoutParams params = child.getLayoutParams(); if (params == null) { params = generateDefaultLayoutParams(); if (params == null) { throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null"); } } addView(child, index, params);}
从上面的代码第5行中我们可以看到,系统尝试从我们提供的view中读取布局参数,然而不幸的是,我们的view并没有布局参数,所以params为null。然后在第7行,系统为我们的view生成了一个默认的布局参数。我们跟进
generateDefaultLayoutParams()
这个方法看一下:
/** * Returns a set of default layout parameters. These parameters are requested * when the View passed to {@link #addView(View)} has no layout parameters * already set. If null is returned, an exception is thrown from addView. * * @return a set of default layout parameters or null */protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);}
看,这个方法返回一个宽高都是wrap_content的参数,注释说的也很清楚。所以,当
inflate
方法参数root为空的时候,我们加载的view的宽高最终是 wrap_content
,并不是我们在xml中设置的。所以才出现了上面的情况。那我们怎么解决这个问题呢?这里有两种方法: 第一种 ,很自然会想到,我们上面说过了,当我们的root不为空的时候,系统会根据root为我们生成的view添加一个布局参数,这样我们的view就可以显示出原来的样子了。改动很简单,只需要将onCreate方法中
View view = LayoutInflater.from(this).inflate(R.layout.button_layout, null);
改成
View view = LayoutInflater.from(this).inflate(R.layout.button_layout, layout, false);
这样系统就可以自动读取xml文件并为我们的view生成布局参数。效果如下:
第二种,我们可以在button这个空间外面添加一层父控件,这样虽然我们依然使用inflate(R.layout.button_layout, null)
这个方法来读取xml文件,并将view设置为wrap_content
,但是此时的view是我们包裹button的外层父控件,所以并不会影响我们的button控件,修改的xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
运行后的结果是这样的:
好了,现在我们来总结一下,当我们调用(或者最终调用了)inflate(int resource, ViewGroup root, boolean attachToRoot)
方法时:
1、如果root为空,那么系统将会返回resource代表的xml的view,并且没有读取xml的参数,也就是view的布局参数为空。需要自行处理。
2、如果root不为空,attachToRoot为false,那么系统将会返回resource代表的xml的view,并读取xml的参数,为view设置布局参数,view不会加入到root中,root只是用来为view生成布局参数而已。
3、如果root不为空,attachToRoot为true,系统将会生成resource代表的xml的view,并为其设置布局参数,然后将view加入到root中作为root的子view,最后返回root。
所以,参数不同时,方法进行的操作不同,返回的结果也有所不同。
四、参考
首先是郭神的博客:http://blog.csdn.net/guolin_blog/article/details/12921889
参照了其中的一些例子:http://bxbxbai.github.io/2014/11/19/make-sense-of-layoutinflater/
一个新浪博客,写的还可以,头像也不错:http://blog.sina.com.cn/s/blog_5da93c8f0100xm6n.html
更多相关文章
- Android官方架构组件LiveData: 观察者模式领域二三事
- Android(安卓)UnitTest
- 某android平板项目开发笔记--自定义sharepreference UI
- Android(安卓)小米盒子游戏手柄按键捕获 - 能获取到的 home 键依
- [Unity3D]Unity3D游戏开发之Unity与Android交互调用研究
- Intent 全面理解
- Using Dagger2 in Android
- 【转】Android最佳性能实践(三)——高性能编码优化
- 仿豌豆荚实现android连接pc方法