用recyclerview,给item布局使用了match_parent属性,运行后不起作用。查了下。是在onCreateViewHolder中加载布局时候出了问题。
一开始用的View.Inflate方法。查看源码后,发现View.inflate也是调用了LayoutInflat而的inflate方法
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
而在LayoutInflater中,最后调用的是
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
···
}
分析源码
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);
}
}
要执行setLayoutParams方法,需要root不能为空,切attachToRoot为false。感觉有空LayoutInflater还得再看一下。这里有hongyan大神的一篇讲LayoutInflater的。感觉还是得仔细看一下。