RecyclerView的列表布局中match_parent失效的解决方法
来源:互联网 发布:智能数据盒子 编辑:程序博客网 时间:2024/05/19 21:43
今天在学习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
0 0
- RecyclerView的列表布局中match_parent失效的解决方法
- RecyclerView控件布局的"match_parent"属性失效
- RecyclerView控件列表项布局match_parent属性失效的根本原理
- RecyclerView控件列表项布局match_parent属性失效的根本原理
- RecyclerView的使用方法以及item布局"match_parent"属性失效
- RecyclerView中item布局的"match_parent"属性失效--LayoutInflate的深入了解
- RecyclerView match_parent 不起作用的解决方法
- RecyclerView item中match_parent失效
- 解决 RecyclerView item布局的match_parent无效
- RecyclerView中的item的match_parent属性失效问题解决方案。
- RecyclerView中的item的match_parent属性失效问题解决方案
- RecycleView添加条目布局match_parent失效的问题
- CoordinatorLayout中,有水平RecyclerView,导致appbar_scrolling_view_behavior失效的解决方法
- 关于自定义Dialog 中match_parent 属性 失效的问题
- android中RecyclerView使用自定义的列表布局
- 关于布局中LinearLayout的fill_parent失效的解决方法
- MATCH_PARENT是什么类型的布局
- Android布局中match_parent和fill_parent的区别
- BZOJ2763: [JLOI2011]飞行路线
- 冒泡法实现链表排序
- NOIP模拟题 [LIS][建图][递推][容斥]
- 邮件服务器
- python try/except/finally
- RecyclerView的列表布局中match_parent失效的解决方法
- 获取mysql数据库中的自增主键属性值和非自增主键属性值的方法
- 动态代理
- sparkmllib线性回归源码学习
- 数据结构之串—关键词索引表
- Chat 聊天界面
- 欢迎使用CSDN-markdown编辑器
- URAL 1036 Lucky Tickets 【dp】【高精度】
- 写LCD驱动程序步骤