您的位置:首页 > 其它

RecyclerView中item布局的"match_parent"属性失效--LayoutInflate的深入了解

2017-03-15 11:23 597 查看
用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的。感觉还是得仔细看一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息