RecyclerView显示Item布局不一致
2016-03-28 09:46
387 查看
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;
相关文章推荐
- 编译spark1.6.0出现 Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.4.0:exec (sparkr-pkg)
- 集合的遍历修改(删除)
- C#线程调用带参数的方法 ~
- 也说说TIME_WAIT状态
- c#截取后台窗口的图片
- 【Python】Django CSRF问题
- Linux mail命令的用法
- C#利用GDI绘制常见图形和文字
- unity5.3 场景烘焙
- httpd服务停止自动发送告警邮件
- OpenCV学习笔记---HighGUI的初步
- C 结构体
- jquery滚动条美化插件
- ios-点击图片放大,背景变半透明
- 全局唯一标识
- Python垃圾回收机制
- poj-2109-Power of Cryptography
- centos系统ps命令详解
- C#中AppDomain.CurrentDomain.BaseDirectory及各种路径获取方法
- 1分钟教会你使用Gson 解析json数据