无意间看到一个帖子,标题:一个难倒 3年 android开发经验 ” 工程师 ” 的 “bug”,链接地址:http://www.2cto.com/kf/201602/489364.html,所描述的问题就是通过填充器动态添加View对象的时候发现view中的宽高失效,而原帖作者所采用的方式是重新设置布局参数,方法如下代码所示:
ll_container=(LinearLayout) findViewById(R.id.ll_container);
btn=(Button) LayoutInflater.from(this).inflate(R.layout.my_button, null);
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(200,200);
btn.setLayoutParams(lp);
ll_container.addView(btn);
看到这个问题之后非常怀疑,觉得非常奇怪,为什么原来xml中的宽度和高度消失了,也是带着这个疑问开始各种搜索,最后通过查看源代码得到了答案,在这里分享给大家。
首先inflate有两个供用户调用的重载方法,分别是:
1、 public View inflate(int resource, ViewGroup root)
2、public View inflate(int resource, ViewGroup root, boolean attachToRoot)
而我们常用的是第一个,而且习惯将root设置为null;
先看第一个方法的源码:
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
看见了吗,其实也是调用的而第二个重载方法,三个参数分别是:view的资源id,装载view的父容器,是否依附到父容器的布尔标记。
下面我们就要进入inflate(int resource, ViewGroup root, boolean attachToRoot)源码中,
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();
}
}
这个方法其实做的事情就是将view的xml文件读取到xml解析器中,然后传递到另外一个inflate重载方法中,
最核心的就在这个方法中,下面来看这个方法中的源代码:
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;