关于inflate时LayoutParams不生效的问题
最简单的方法是在外层套一层布局
不想套的可以向下看
我个人经常用LayoutInflater中的inflate方法
可能有些朋友还经常用View.inflate方法
View.inflate方法其实就是简单包装了下LayoutInflater.inflate方法
我们最多的用法就是
LayoutInflater.inflate(layoutID,null)
那么我们看下这个方法
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
这里调用了三个参数的方法
public View inflate(int resource, 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();
}
}
又调用了inflate(parser, root, attachToRoot);方法
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
...
final AttributeSet attrs = Xml.asAttributeSet(parser);
...
View result = root; //result 是返回的结果,这里先赋值为root,传进来的ViewGroup
try {
...
final String name = parser.getName();
if (TAG_MERGE.equals(name)) {
...
} else {
final View temp = createViewFromTag(root, name, attrs, false); //创建根view对象
ViewGroup.LayoutParams params = null;
if (root != null) {
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params); //重点在这里
}
}
rInflate(parser, temp, attrs, true, true);
if (root != null && attachToRoot) {
root.addView(temp, params); //如果有传了root并且attachToRoot为true那么直接添加到root, 下面会直接返回result,这时result为root
}
if (root == null || !attachToRoot) {
result = temp; //这里将result改为了根view
}
}
} catch (XmlPullParserException e) {
...
} finally {
...
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}
从以上代码我们看到
我们调用LayoutInflater.inflate(layoutID,null)方法时
其实root为null,attachToRoot为false
那么
if (root != null) {
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params); //重点在这里
}
}
这块代码就不会执行
LayoutParams就不会被添加
我们现在要加LayoutParams, root就不能为空
而用
LayoutInflater.inflate(layoutID,null)
方法传入root后返回的就是传入的root对象而不是根view
在下面我们看到这段代码
if (root == null || !attachToRoot) {
result = temp;
}
那么只要让root设置为空或者attachToRoot为false就行了
但上面我们不能将root传空
那么最终解决方法就是
LayoutInflater.inflate(layoutID,root,false)
这种方法有缺陷哦,可能会产生ClassCastException使用时应注意