今天在学习RecyclerView的列表布局中发现了一个很头疼的问题:我给列表中的item设置的布局的宽度明明是match_parent,可是呈现出来的效果却是wrap_content,也就是每个item的宽度都没有填充屏幕。
在onCreateViewHolder方法中,我填充item的布局是这样写的:
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = View.inflate(context, R.layout.item_recyclerview, null);
}
但在网上查了一下,有人建议采用下面的写法:
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View itemView = View.inflate(context, R.layout.item_recyclerview, null);
LayoutInflater inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.item_recyclerview,parent,true);
return new ViewHolder(itemView);
}
这个写法添加了parent参数,但是运行之后却报出下面的错:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.
说明我们要填充的View已经有了一个父View,必须从父View中移除才能使用,对这个错误我也不是很理解,但是这个bug还是没有解决,继续寻找方法,最后试了下面这一种,可以了:
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View itemView = inflater.inflate(R.layout.item_recyclerview,null,true);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
itemView.setLayoutParams(lp);
return new ViewHolder(itemView);
}
这里的写法的意思item作为子布局,向父布局RecyclerView传递了自己需要的布局数据,则宽是match_parent,高是wrap_content。运行之后,发现match_parent终于发挥作用了。
参考文章:http://blog.csdn.net/ll530304349/article/details/52605202