RecyclerView显示Item布局不一致
来源:互联网 发布:单片机在汽车的指令 编辑:程序博客网 时间:2024/05/24 01:21
RecyclerView显示Item布局不一致
在自定义RecyclerAdapter的时候,在重写onCreateViewHolder方法是使用了
@Override public H onCreateViewHolder(ViewGroup parent, int viewType) { View view=View.inflate(context,layoutId,null); return view; }
进行生成布局,结果发现生成的布局没有LayoutParams。以前自定义View的时候发现,LayoutParams是由于ViewGroup生成的,因为这里添加的ViewGroup为null。所以并不会生成LayoutParams。结果在RecyclerView的getViewForPosition方法中检查了有没有LayoutParams如果没有的话就调用LayoutManager的generateDefaultLayoutParams生成默认的LayoutParames。代码段如下:
final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams(); final LayoutParams rvLayoutParams; if (lp == null) { rvLayoutParams = (LayoutParams) generateDefaultLayoutParams(); holder.itemView.setLayoutParams(rvLayoutParams); } else if (!checkLayoutParams(lp)) { rvLayoutParams = (LayoutParams) generateLayoutParams(lp); holder.itemView.setLayoutParams(rvLayoutParams); } else { rvLayoutParams = (LayoutParams) lp; }
而在LinearLayoutManager中generateDefaultLayoutParams方法实现如下。
/** * {@inheritDoc} */ @Override public LayoutParams generateDefaultLayoutParams() { return new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); }
最终会造成RecycleView的显示效果与布局文件不一致。后来使用了LayoutInflater来填充布局。
@Override public H onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(layoutId, parent, false); return getInstanceOfH(view); }
查看LayoutInflater源码发现inflate最后的参数如果是false的话就不会将生成的View添加到parent。但是会根据parent产生相应的LayoutParams 。源码如下:
* @param attachToRoot Whether the inflated hierarchy should be attached to * the root parameter? If false, root is only used to create the * correct subclass of LayoutParams for the root view in the XML.
因为在onCreateViewHolder中产生的View不能由我们手动添加到RecycleView中所以最后的参数只能是false;
1 0
- RecyclerView显示Item布局不一致
- RecyclerView显示与定义的Item布局不一致的问题
- RecyclerView显示多种Item布局
- Android RecyclerView显示不同item布局
- RecyclerView多种item布局
- RecyclerView实现多种item布局
- CoordinatorLayout +RecyclerView+加载不同布局的item
- RecyclerView之添加不同的item布局
- RecyclerView多布局与Item点击事件
- CoordinatorLayout +RecyclerView+加载不同布局的item
- 动态改变recyclerview的item的布局
- RecyclerView多样式Item布局设计
- 解决 RecyclerView item布局的match_parent无效
- listview item显示不同布局
- Android RecyclerView 动画展开item显示详情
- RecyclerView中显示不同的item
- RecyclerView显示不同的类型的item
- RecyclerView 分组 item显示不同view
- 打开SQlite数据库
- 自定义控件三部曲之绘图篇(六)——Path之贝赛尔曲线和手势轨迹、水波纹效果
- PAT1028人口普查(20)
- C#线程调用带参数的方法 ~
- 集合的遍历修改(删除)
- RecyclerView显示Item布局不一致
- Windows下ffmpeg录制视频命令
- leangoo大讲堂--北京站
- django get_object_or_404
- uboot 和内核的分区关系
- 把 notepad++ 的 tab 设为4个空格a
- 自主学习之RxSwift(二) -----flatMap
- problem-1002-田忌赛马
- Android优化应用启动速度