android: LayoutInflater使用
1、 题外话
相信大家对LayoutInflate都不陌生,特别在ListView的Adapter的getView方法中基本都会出现,使用inflate方法去加载一个布局,用于ListView的每个Item的布局。Inflate有三个参数,我在初学Android的时候这么理解的:
对于Inflate的三个参数(int resource, ViewGroup root, boolean attachToRoot)
如果inflate(layoutId, null )则layoutId的最外层的控件的宽高是没有效果的
如果inflate(layoutId, root, false ) 则认为和上面效果是一样的
如果inflate(layoutId, root, true ) 则认为这样的话layoutId的最外层控件的宽高才能正常显示
如果你也这么认为,那么你有就必要好好阅读这篇文章,因为这篇文章首先会验证上面的理解是错误的,然后从源码角度去解释,最后会从ViewGroup与View的角度去解释。
2、 实践是验证真理的唯一标准
下面我写一个特别常见的例子来验证上面的理解是错误的,一个特别简单的ListView,每个Item中放一个按钮:
Activity的布局文件:
- <ListView xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/id_listview"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" >
- </ListView>
ListView的Item的布局文件:
- <Button xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/id_btn"
- android:layout_width="120dp"
- android:layout_height="120dp" >
- </Button>
ListView的适配器:
- package com.example.zhy_layoutinflater;
- import java.util.List;
- import android.content.Context;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.BaseAdapter;
- import android.widget.Button;
- public class MyAdapter extends BaseAdapter
- {
- private LayoutInflater mInflater;
- private List<String> mDatas;
- public MyAdapter(Context context, List<String> datas)
- {
- mInflater = LayoutInflater.from(context);
- mDatas = datas;
- }
- @Override
- public int getCount()
- {
- return mDatas.size();
- }
- @Override
- public Object getItem(int position)
- {
- return mDatas.get(position);
- }
- @Override
- public long getItemId(int position)
- {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent)
- {
- ViewHolder holder = null;
- if (convertView == null)
- {
- holder = new ViewHolder();
- convertView = mInflater.inflate(R.layout.item, null);
- // convertView = mInflater.inflate(R.layout.item, parent ,false);
- // convertView = mInflater.inflate(R.layout.item, parent ,true);
- holder.mBtn = (Button) convertView.findViewById(R.id.id_btn);
- convertView.setTag(holder);
- } else
- {
- holder = (ViewHolder) convertView.getTag();
- }
- holder.mBtn.setText(mDatas.get(position));
- return convertView;
- }
- private final class ViewHolder
- {
- Button mBtn;
- }
- }
主Activity:
- package com.example.zhy_layoutinflater;
- import java.util.Arrays;
- import java.util.List;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.ListView;
- public class MainActivity extends Activity
- {
- private ListView mListView;
- private MyAdapter mAdapter;
- private List<String> mDatas = Arrays.asList("Hello", "Java", "Android");
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- mListView = (ListView) findViewById(R.id.id_listview);
- mAdapter = new MyAdapter(this, mDatas);
- mListView.setAdapter(mAdapter);
- }
- }
好了,相信大家对这个例子都再熟悉不过了,没啥好说的,我们主要关注getView里面的inflate那行代码:下面我依次把getView里的写成:
1、convertView = mInflater.inflate(R.layout.item, null);
2、convertView = mInflater.inflate(R.layout.item, parent ,false);
3、convertView = mInflater.inflate(R.layout.item, parent ,true);
分别看效果图:
图1:
图2:
图3:
- FATAL EXCEPTION: main
- java.lang.UnsupportedOperationException:
- addView(View, LayoutParams) is not supported in AdapterView
嗯,没错没有图3,第三种写法会报错。
由上面三行代码的变化,产生3个不同的结果,可以看到
inflater(resId, null )的确不能正确处理宽高的值,但是inflater(resId,parent,false)并非和inflater(resId, null )效果一致,它可以看出完美的显示了宽和高。
而inflater(resId,parent,true)报错了(错误的原因在解析源码的时候说)。
由此可见:文章开始提出的理解是绝对错误的。
3、源码解析
下面我通过源码来解释,这三种写法真正的差异
这三个方法,最终都会执行下面的代码:
- public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
- synchronized (mConstructorArgs) {
- final AttributeSet attrs = Xml.asAttributeSet(parser);
- Context lastContext = (Context)mConstructorArgs[0];
- 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 (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, attrs, false);
- } else {
- // Temp is the root view that was found in the xml
- View temp;
- if (TAG_1995.equals(name)) {
- temp = new BlinkLayout(mContext, attrs);
- } else {
- temp = createViewFromTag(root, name, 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
- rInflate(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 (IOException 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;
- }
- return result;
- }
- }
第6行:首先声明了View result = root ;//最终返回值为result
第43行执行了:temp = createViewFromTag(root, name, attrs);创建了View
然后直接看48-59:
- if(root!=null)
- {
- params = root.generateLayoutParams(attrs);
- if (!attachToRoot)
- {
- temp.setLayoutParams(params);
- }
- }
可以看到,当root不为null,attachToRoot为false时,为temp设置了LayoutParams.
继续往下,看73-75行:
- if (root != null && attachToRoot)
- {
- root.addView(temp, params);
- }
当root不为null,attachToRoot为true时,将tmp按照params添加到root中。
然后78-81行:
- if (root == null || !attachToRoot) {
- result = temp;
- }
如果root为null,或者attachToRoot为false则,将temp赋值给result。
最后返回result。
从上面的分析已经可以看出:
Inflate(resId , null ) 只创建temp ,返回temp
Inflate(resId , parent, false )创建temp,然后执行temp.setLayoutParams(params);返回temp
Inflate(resId , parent, true ) 创建temp,然后执行root.addView(temp, params);最后返回root
由上面已经能够解释:
Inflate(resId , null )不能正确处理宽和高是因为:layout_width,layout_height是相对了父级设置的,必须与父级的LayoutParams一致。而此temp的getLayoutParams为null
Inflate(resId , parent,false ) 可以正确处理,因为temp.setLayoutParams(params);这个params正是root.generateLayoutParams(attrs);得到的。
Inflate(resId , parent,true )不仅能够正确的处理,而且已经把resId这个view加入到了parent,并且返回的是parent,和以上两者返回值有绝对的区别,还记得文章前面的例子上,MyAdapter里面的getView报的错误:
- java.lang.UnsupportedOperationException:
- addView(View, LayoutParams) is not supported in AdapterView
这是因为源码中调用了root.addView(temp, params);而此时的root是我们的ListView,ListView为AdapterView的子类:
直接看AdapterView的源码:
- @Override
- public void addView(View child) {
- throw new UnsupportedOperationException("addView(View) is not supported in AdapterView");
- }
可以看到这个错误为啥产生了。
4、 进一步的解析
上面我根据源码得出的结论可能大家还是有一丝的迷惑,我再写个例子论证我们上面得出的结论:
主布局文件:
- <Button xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:id="@+id/id_btn"
- android:layout_width="120dp"
- android:layout_height="120dp"
- android:text="Button" >
- </Button>
主Activity:
- package com.example.zhy_layoutinflater;
- import android.app.ListActivity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- public class MainActivity extends ListActivity
- {
- private LayoutInflater mInflater;
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- mInflater = LayoutInflater.from(this);
- View view1 = mInflater.inflate(R.layout.activity_main, null);
- View view2 = mInflater.inflate(R.layout.activity_main,
- (ViewGroup)findViewById(android.R.id.content), false);
- View view3 = mInflater.inflate(R.layout.activity_main,
- (ViewGroup)findViewById(android.R.id.content), true);
- Log.e("TAG", "view1 = " + view1 +" , view1.layoutParams = " + view1.getLayoutParams());
- Log.e("TAG", "view2 = " + view2 +" , view2.layoutParams = " + view2.getLayoutParams());
- Log.e("TAG", "view3 = " + view3 );
- }
- }
可以看到我们的主Activity并没有执行setContentView,仅仅执行了LayoutInflater的3个方法。
注:parent我们用的是Activity的内容区域:即android.R.id.content,是一个FrameLayout,我们在setContentView(resId)时,其实系统会自动为了包上一层FrameLayout(id=content)。
按照我们上面的说法:
view1的layoutParams 应该为null
view2的layoutParams 应该不为null,且为FrameLayout.LayoutParams
view3为FrameLayout,且将这个button添加到Activity的内容区域了(因为R.id.content代表Actvity内容区域)
下面看一下输出结果,和Activity的展示:
- 07-27 14:17:36.703: E/TAG(2911): view1 = android.widget.Button@429d1660 , view1.layoutParams = null
- 07-27 14:17:36.703: E/TAG(2911): view2 = android.widget.Button@42a0e120 , view2.layoutParams = android.widget.FrameLayout$LayoutParams@42a0e9a0
- 07-27 14:17:36.703: E/TAG(2911): view3 = android.widget.FrameLayout@42a0a240
效果图:
可见,虽然我们没有执行setContentView,但是依然可以看到绘制的控件,是因为
View view3 = mInflater.inflate(R.layout.activity_main,(ViewGroup)findViewById(android.R.id.content), true);
这个方法内部已经执行了root.addView(temp , params); 上面已经解析过了。
也可以看出:和我们的推测完全一致,到此已经完全说明了inflate3个重载的方法的区别。相信大家以后在使用时也能选择出最好的方式。不过下面准备从ViewGroup和View的角度来说一下,为啥layoutParams为null,就不能这确的处理。
5、从ViewGroup和View的角度来解析
如果大家对自定义ViewGroup和自定义View有一定的掌握,肯定不会对onMeasure方法陌生:
ViewGroup的onMeasure方法所做的是:
为childView设置测量模式和测量出来的值。
如何设置呢?就是根据LayoutParams。
如果childView的宽为:LayoutParams. MATCH_PARENT,则设置模式为MeasureSpec.EXACTLY,且为childView计算宽度。
如果childView的宽为:固定值(即大于0),则设置模式为MeasureSpec.EXACTLY,且将lp.width直接作为childView的宽度。
如果childView的宽为:LayoutParams. WRAP_CONTENT,则设置模式为:MeasureSpec.AT_MOST
高度与宽度类似。
View的onMeasure方法:
主要做的就是根据ViewGroup传入的测量模式和测量值,计算自己应该的宽和高:
一般是这样的流程:
如果宽的模式是AT_MOST:则自己计算宽的值。
如果宽的模式是EXACTLY:则直接使用MeasureSpec.getSize(widthMeasureSpec);
对于最后一块,如果不清楚,不要紧,以后我会在自定义ViewGroup和自定义View时详细讲解的。
大概就是这样的流程,真正的绘制过程肯定比这个要复杂,就是为了说明如果View的宽和高如果设置为准确值,则一定依赖于LayoutParams,所以我们的inflate(resId,null)才没能正确处理宽和高。
android: LayoutInflater使用的更多相关文章
- Android LayoutInflater布局填充器
Android LayoutInflater布局填充器 把一份xml布局文件转为View对象,这就是layoutinflater的作用. 对于一个没有被载入或者想要动态载入的界面,都需要使用Layou ...
- [旧][Android] LayoutInflater 工作流程
备注 原发表于2016.06.20,资料已过时,仅作备份,谨慎参考 前言 感觉很长时间没写文章了,这个星期因为回家和处理项目问题,还是花了很多时间的.虽然知道很多东西如果只是看一下用一次,很快就会遗忘 ...
- Android LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)的参数理解
方法inflate(int resource, ViewGroup root, boolean attachToRoot) 中 第一个参数传入布局的资源ID,生成fragment视图,第二个参数是视图 ...
- Android LayoutInflater详解
在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且 ...
- 转载《Android LayoutInflater详解》
在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例 ...
- Android LayoutInflater原理分析,带你一步步深入了解View(一)
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/12921889 有不少朋友跟我反应,都希望我可以写一篇关于View的文章,讲一讲Vi ...
- Android LayoutInflater详解(转)
在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例 ...
- Android LayoutInflater详解 (转)
在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例 ...
- Android LayoutInflater原理分析
相信接触Android久一点的朋友对于LayoutInflater一定不会陌生,都会知道它主要是用于加载布局的.而刚接触Android的朋友可能对LayoutInflater不怎么熟悉,因为加载布局的 ...
- Android LayoutInflater 动态地添加删除View
我想实现点击一个按钮(或其他的事件)添加或删除View,网上找到了LayoutInflater这个类. 下面是我自己一些经验: android官网上LayoutInflater的API:http:// ...
随机推荐
- 【前端】三个bug
目录 一.Array对象的indexOf() 二.使用jquery,clone()下拉框问题 三.jquery获取获取html5的data-*属性 一.Array对象的indexOf() 1.inde ...
- CCF2015122消除类游戏(C语言版)
问题描述 消除类游戏是深受大众欢迎的一种游戏,游戏在一个包含有n行m列的游戏棋盘上进行,棋盘的每一行每一列的方格上放着一个有颜色的棋子,当一行或一列上有连续三个或更多的相同颜色的棋子时,这些棋子都被消 ...
- PHP对Url中的汉字进行编码和解码
有的新手朋友们对于url编码解码这个概念,或许有点陌生.但是如果这么说,当我们在浏览各大网页时,可能发现有的url里有一些特殊符号比如#号,&号,_号或者汉字等等,那么为了符合url的规范,存 ...
- 利用反射创建User类的对象
package com.bjpowernode; public class User { private int age; public String name; public void m1() { ...
- ERP退货系统管理(四十五)
添加的存储过程:(添加退货申请信息的存储过程) CREATE PROCEDURE [dbo].[BioBackSendGoods_ADD] @SendBackID INT OUTPUT, ), @Ap ...
- POJ 2718【permutation】
POJ 2718 问题描述: 给一串数,求划分后一个子集以某种排列构成一个数,余下数以某种排列构成另一个数,求这两个数最小的差,注意0开头的处理. 超时问题:一开始是得到一个数列的组合之后再从中间进行 ...
- mysql 不区分大小写的解决
mysql查询默认是不区分大小写的 如: select * from some_table where str=‘abc';select * from some_table where str='AB ...
- 043 HIVE中的HQL操作
1.字段查询 select empno,ename from emp; 2.过滤where,limit,distinct select * from emp where sal >2500; s ...
- hdu 4513 最长不下降回文序列【manacher】
<题目链接> 吉哥又想出了一个新的完美队形游戏! 假设有n个人按顺序站在他的面前,他们的身高分别是h[1], h[2] ... h[n],吉哥希望从中挑出一些人,让这些人形成一个新的队形 ...
- Spring Boot 入门详细分析
推荐阅读: 我们为什么要学习 Spring Boot 我们搭建 Spring Boot 项目,可以使用 Spring 为我们提供的初始化网站,那个可能不太方便,今天呢,我们就来说说如何使用 IDEA ...