浅析Android中的inflate
部分转载自这里
LayoutInflater.from(context).inflate(layout, root,attachToRoot);
LayoutInflater.inflate
一共有很多个重载。最终都会调用到以下这个方法。
先看例子
textview_layout
|
|
textview_layout_parent
|
|
activity
|
|
最终运行
分析
|
|
从上面的源码分析我们可以看出inflate方法的参数含义:
inflate(xmlId, null); 只创建temp的View,然后直接返回temp。
inflate(xmlId, parent); 创建temp的View,然后执行root.addView(temp, params);最后返回root。
inflate(xmlId, parent, false); 创建temp的View,然后执行temp.setLayoutParams(params);然后再返回temp。
inflate(xmlId, parent, true); 创建temp的View,然后执行root.addView(temp, params);最后返回root。
inflate(xmlId, null, false); 只创建temp的View,然后直接返回temp。
inflate(xmlId, null, true); 只创建temp的View,然后直接返回temp。
mInflater.inflate(R.layout.textview_layout, null)
不能正确处理我们设置的宽和高是因为layout_width,layout_height是相对了父级设置的,而此temp的getLayoutParams为null。mInflater.inflate(R.layout.textview_layout, parent)
能正确显示我们设置的宽高是因为我们的View在设置setLayoutParams时params = root.generateLayoutParams(attrs)
不为空。
Inflate(resId , parent,false ) 可以正确处理,因为temp.setLayoutParams(params);这个params正是root.generateLayoutParams(attrs);得到的。mInflater.inflate(R.layout.textview_layout, null, true)
与mInflater.inflate(R.layout.textview_layout, null, false)
不能正确处理我们设置的宽和高是因为layout_width,layout_height是相对了父级设置的,而此temp的getLayoutParams为null。textview_layout_parent.xml作为item可以正确显示的原因是因为TextView具备上级ViewGroup,上级ViewGroup的layout_width,layout_height会失效,当前的TextView会有效而已。
inflate(xmlId, parent)
和inflate(xmlId, parent,true)
是会直接崩溃的。原因是AdapterView源码中调用了root.addView(temp, params);而此时的root是我们的ListView,ListView为AdapterView的子类,所以我们看下AdapterView抽象类中addView源码即可明白为啥了,如下:
|
|