LayoutInflator#Inflate(...)
这个标题起的有点夸张哈,但是LayoutInflater这个类的一些用法,在Android开发者使用的过程中,确实存在着一些很普遍的误区,最起码我研究的这么多小项目的源代码,基本上都在错误的使用这个类。今天,看到了一篇文章讲LayoutInflater的用法,瞬间感觉自己对这个类确实不够了解,于是简单的看了下LayoutInflater类的源代码,对这个类有了新的认识。
首先,LayoutInflater这个类是用来干嘛的呢?
我们最常用的便是LayoutInflater的inflate方法,这个方法重载了四种调用方式,分别为:
1. public View inflate(int resource, ViewGroup root)
2. public View inflate(int resource, ViewGroup root, boolean attachToRoot)
3.public View inflate(XmlPullParser parser, ViewGroup root)
4.public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
这四种使用方式中,我们最常用的是第一种方式,inflate方法的主要作用就是将xml转换成一个View对象,用于动态的创建布局。虽然重载了四个方法,但是这四种方法最终调用的,还是第四种方式。第四种方式也很好理解,内部实现原理就是利用Pull解析器,对Xml文件进行解析,然后返回View对象。
我们以我们经常使用的第一种形式为例,你在重写BaseAdapter的getView方法的时候是否这样做过
1
2
3
4
5
6
|
public View getView( int position, View convertView, ViewGroup parent) {
if (convertView == null ) {
convertView = inflate(R.layout.item_row, null );
}
return convertView;
}
|
inflate方法有三个参数,分别是
1.resource布局的资源id
2.root填充的根视图
3.attachToRoot是否将载入的视图绑定到根视图中
在这个例子中,我们将root参数设为空,功能确实实现了,但是这里还隐藏着一个隐患,这种方式并不是inflate正确的使用姿势,下面我们通过一个Demo,来说一下这样使用造成的弊端。
首先,我们建立一个这样的项目
<喎�"/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+1eLA78j9uPa958Pmo6zSu7j21ve958Pmo6zBvbj2suLK1L3nw+ajrLK8vtbOxLz+1tCjrNb3vefD5ta7uLrU8L3nw+bM+Neqo6zBvbj2suLK1L3nw+a2vMrH0ru49rzytaW1xExpc3R2aWV3o6xpdGVtsry+1s/Uyr7Qp7n7yOfPwjwvcD4KPHA+PGltZyBzcmM9"/uploadfile/Collfiles/20140701/20140701085327132.jpg" alt="\">
对应的布局文件如下
1
2
3
4
5
6
|
<!--?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= "60dp" android:background= "@android:color/holo_orange_light" android:gravity= "center" android:orientation= "vertical" >
<textview android:id= "@+id/tv" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "11" android:textcolor= "@android:color/black" android:textsize= "22sp" >
</textview></linearlayout>
|
OneActivity的代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
public class OneActivity extends Activity {
private ListView list1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
list1 = (ListView) findViewById(R.id.list1);
list1.setAdapter( new MyAdapter( this ));
}
private class MyAdapter extends BaseAdapter {
private LayoutInflater inflater;
MyAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return 20 ;
}
@Override
public Object getItem( int position) {
return position;
}
@Override
public long getItemId( int position) {
return position;
}
@Override
public View getView( int position, View convertView, ViewGroup parent) {
if (convertView == null ) {
convertView = inflater.inflate(R.layout.item_list, null );
}
TextView tv = (TextView) convertView.findViewById(R.id.tv);
tv.setText(position+ "" );
return convertView;
}
}
}
|
TwoActivity的代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
public class TwoActivity extends Activity {
private ListView list2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
list2 = (ListView) findViewById(R.id.list2);
list2.setAdapter( new MyAdapter( this ));
}
private class MyAdapter extends BaseAdapter {
private LayoutInflater inflater;
MyAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return 20 ;
}
@Override
public Object getItem( int position) {
return position;
}
@Override
public long getItemId( int position) {
return position;
}
@Override
public View getView( int position, View convertView, ViewGroup parent) {
if (convertView == null ) {
convertView = inflater.inflate(R.layout.item_list, parent, false );
}
TextView tv = (TextView) convertView.findViewById(R.id.tv);
tv.setText(position + "" );
return convertView;
}
}
}
|
两个文件最关键的区别就一句话,
在getView方法中,OneActivity是
convertView = inflater.inflate(R.layout.item_list, null);
在getView方法中,TwoActivity是
convertView = inflater.inflate(R.layout.item_list, parent,false);
我们先看一下显示效果,再说两者的区别
OneActivity效果
TwoActivity的显示效果
我们可以很明显的看出来,使用第一种方式,根布局的高度设置60dp没有起作用,系统还是按照包裹内容的方式加载的,为什么会产生这种效果呢?我们从需要inflate方法的源代码中找一下答案。
首先,方式一的源代码实现
1
2
3
|
public View inflate(XmlPullParser parser, ViewGroup root) {
return inflate(parser, root, root != null );
}
|
当我们使用方式一,并且第二个参数传入null的时候,默认调用的是下面的方法,并且attachToRoot是false
1
2
3
4
5
6
7
8
9
|
public View inflate( int resource, ViewGroup root, boolean attachToRoot) {
if (DEBUG) System.out.println( "INFLATING from resource: " + resource);
XmlResourceParser parser = getContext().getResources().getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
|
在这一个方法中,pull解析器将资源id转化成XmlResourceParser对象,又传给了第四种方式,所以我们需要重点看的还是第四种方式是如何实现的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate" );
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 ;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}</merge>
|
代码比较长,我们重点关注下面的代码
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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);
}
}
|
这些代码的意思就是,当我们传进来的root参数不是空的时候,并且attachToRoot是false的时候,也就是上面的TwoActivity的实现方式的时候,会给temp设置一个LayoutParams参数。那么这个temp又是干嘛的呢?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<pre name= "code" class = "java" > // 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;
}</pre><br>
<br>
<p></p>
<pre class = "brush:java;" ></pre>
<br>
现在应该明白了吧,当我们传进来的root不是 null ,并且第三个参数是 false 的时候,这个temp就被加入到了root中,并且把root当作最终的返回值返回了。而当我们设置root为空的时候,没有设置LayoutParams参数的temp对象,作为返回值返回了。
<p></p>
<p>因此,我们可以得出下面的结论:</p>
<p> 1 .若我们采用convertView = inflater.inflate(R.layout.item_list,
null );方式填充视图,item布局中的根视图的layout_XX属性会被忽略掉,然后设置成默认的包裹内容方式</p>
<p> 2 .如果我们想保证item的视图中的参数不被改变,我们需要使用convertView
= inflater.inflate(R.layout.item_list, parent, false );这种方式进行视图的填充</p>
<p> 3 .除了使用这种方式,我们还可以设置item布局的根视图为包裹内容,然后设置内部控件的高度等属性,这样就不会修改显示方式了。</p>
<p><br>
</p>
<p>最后,给出那篇文章的链接http: //blog.jobbole.com/72156/
大家可以去看看</p>
|
LayoutInflator#Inflate(...)相关推荐
- Android --- View.inflate()的详细介绍
误用 LayoutInflater 的 inflate() 方法已经不是什么稀罕事儿了-- 做 Android 开发做久了,一定会或多或少地对布局的渲染有一些懵逼: 1.View.inflate() ...
- android inflater,探索 Android Inflater.inflate()
android-knowledge.jpg 在 Android 开发中,有很多看起来 "约定俗成" 的代码,有时候不妨停下来想一想深层次的含义.最近我在给 Fragment 填充布 ...
- Android自问自答系列——持续更新ING
Hello,All,我是来自58同城的一名Android开发工程师,在58集团从事APP的开发工作.在日常的工作和学习过程中我经常会碰到一些好玩的和有意思的Android小知识点,有些知识可能都从未注 ...
- LayoutInflater的inflate函数用法详解
LayoutInflater的inflate函数用法详解 LayoutInflater作用是将layout的xml布局文件实例化为View类对象. 获取LayoutInflater的方法有如下三种: ...
- 带你看懂LayoutInflater中inflate方法
关于inflate问题,我想很多人多多少少都了解一点,网上也有很多关于这方面介绍的文章,但是枯燥的理论或者翻译让很多小伙伴看完之后还是一脸懵逼,so,我今天想通过三个案例来让小伙伴彻底的搞清楚这个东东 ...
- Android LayoutInflater.inflate源码解析
一年多以前看过源码,感觉了解比较透彻了,长时间不经大脑思考,靠曾经总结的经验使用inflate方法,突然发现不知道什么时候忘记其中的原理了,上网查了一些资料,还各有不同,反而把我搞糊涂了,还是自己看源 ...
- LayoutInflater中四种类型inflate方法的介绍
第一种: public View inflate (int resource, ViewGroup root) resource : View 的 layout 的 ID root :如果返回 nul ...
- android LayoutInflater.inflate()的参数及其用法
很多人在网上问LayoutInflater类的用法,以及inflate()方法参数的含义,现解释如下: inflate()的作用就是将一个用xml定义的布局文件查找出来,注意与findViewById ...
- Android之Inflate()方法用途
flate()作用就是将xml定义的一个布局找出来,但仅仅是找出来而且隐藏的,没有找到的同时并显示功能.最近做的一个项目就是这一点让我迷茫了好几天. Android上还有一个与Inflate()类似功 ...
最新文章
- 练习2:课工场响应式导航条_作业帮直播课APP下载最新版入口
- 『模板 高精度计算』
- 记录一下Python-Qt中按钮点击事件无响应解决方案
- java关键字和保留字整合(不定期补充) 转自小码哥
- 读书笔记-《大话数据结构》第二章算法
- 开源应用框架BitAdminCore:更新日志20180817
- python读取配置文件 分段_Python3读写ini配置文件的示例
- Python:进阶操作(1)
- 中兴bsc服务器是什么,中兴BSC内部信令流程介绍
- 缓存MEMCACHE 使用原子性操作add,实现并发锁
- ubuntu-文件管理、编辑
- 编译OpenJDK12:LINK : warning LNK4098: 默认库“LIBCMT”与其他库的使用冲突;请使用 /NODEFAULTLIB:library
- linux ldconfig 刷新动态库,linux下动态共享库的创建,使用与更新(包括ldconfig的使用)g++ -WI -soname...
- wordpress备份和还原和迁移
- 谁能拒绝一个会动的皮卡丘挂件
- 基因相关性——字符串入门
- 什么是项目集,如何有效管理?
- 由七芒星引出来的——关于142857
- Android手机cpu架构详解
- 蓝月传奇服务器维护怎么刷新,蓝月传奇10月12日更新维护公告