本文主要是介绍RecyclerView下拉刷新item间距变大的问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
RecyclerView下拉刷新item间距变大的问题
现在列表类布局是非常常见的布局,大多数都是使用RecyclerView来实现。日前在项目中就有一个页面是列表类的,稍微有些不同的是单个item中需要显示图片,类似朋友圈那样的,这样就嵌套了一个RecyclerView,效果见下图:
相关代码如下:
@Overridepublic void onBindViewHolder(CommonViewHolder viewHolder, int i) {//图片使用的RecyclerView RecyclerView recyclerView = viewHolder.getView(R.id.recyclerview);recyclerView.setVisibility(View.VISIBLE);GridLayoutManager gridLayoutManager = new GridLayoutManager(recyclerView.getContext(), 3);recyclerView.setLayoutManager(gridLayoutManager);GridItemDecoration gridItemDecoration = new GridItemDecoration(3, DensityUtil.dip2px(3));recyclerView.addItemDecoration(gridItemDecoration);recyclerView.setAdapter(new PostListImagesAdapter(data.getPost_pic_url()));recyclerView.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:break;case MotionEvent.ACTION_UP:ContentStartAcHelper.startPostDetailAc(v.getContext(), String.valueOf(data.getPost_id()), data.getPost_type(), false);break;}return false;}});}
这时在下拉刷新时就会发现,图片间的间距每次都会变大,分析上面的代码,大概可猜测到 是recyclerView.addItemDecoration(gridItemDecoration)的问题,在下拉刷新或者上下滑动后,调用onBindViewHolder方法,导致每次都会执行recyclerView.addItemDecoration(gridItemDecoration),点击方法进入源码都发现,此方法会将每次add的Decoration累加起来:
public void addItemDecoration(ItemDecoration decor) {addItemDecoration(decor, -1);}public void addItemDecoration(ItemDecoration decor, int index) {if (mLayout != null) {mLayout.assertNotInLayoutOrScroll("Cannot add item decoration during a scroll or"+ " layout");}if (mItemDecorations.isEmpty()) {setWillNotDraw(false);}if (index < 0) {mItemDecorations.add(decor);} else {mItemDecorations.add(index, decor);}markItemDecorInsetsDirty();requestLayout();}
找到问题所在,那么就好解决了,只要在recyclerView.addItemDecoration时增加判断是否已经有ItemDecoration即可:
if (recyclerView.getItemDecorationCount() == 0 ) {recyclerView.addItemDecoration(gridItemDecoration);}
问题结局!
另外,图片Recyclerview使用的是GridLayoutManager,在图片空白的位置点击是没有效果的,可通过设置setOnTouchListener来实现点击效果,代码见上。
这篇关于RecyclerView下拉刷新item间距变大的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!