RecyclerView StaggeredGridLayoutManager瀑布流边框刷新问题,错位解决
Posted jieth
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RecyclerView StaggeredGridLayoutManager瀑布流边框刷新问题,错位解决相关的知识,希望对你有一定的参考价值。
1.方式--设置统一的ItemDecoration(如果左右边框和中间不对等,可以在xml设置RecyclerView的margin或者padding)
recyclerView.addItemDecoration(new ItemOffsetDecoration(10,5,10,5))
import android.graphics.Rect; import android.view.View; import androidx.recyclerview.widget.RecyclerView; public class ItemOffsetDecoration extends RecyclerView.ItemDecoration { private int left; private int top; private int right; private int bottom; public ItemOffsetDecoration(int left,int top,int right,int bottom) { this.left=left; this.top=top; this.right=right; this.bottom=bottom; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); outRect.set(left,top,right,bottom); } }
2.方法,需要针对左右不同去设置 ItemDecoration
import android.graphics.Rect; import android.view.View; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; public class StaggeredDividerItemDecoration extends RecyclerView.ItemDecoration { private int top,bottom,left1,left2,right1,right2; public StaggeredDividerItemDecoration(int top, int bottom, int left1, int right1, int left2, int right2) { this.top = top; this.bottom = bottom; this.left1 = left1; this.left2 = left2; this.right1 = right1; this.right2 = right2; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { super.getItemOffsets(outRect, view, parent, state); StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams(); // 获取item在span中的下标 int spanIndex = params.getSpanIndex(); // 右 if (spanIndex % 2 == 0) { outRect.left = left1; outRect.right = right1; } else { // item为左 outRect.left = left2; outRect.right = right2; } outRect.top = top; outRect.bottom = bottom; } }
但是会出现一个问题,如果图片高度自适应,ItemDecoration会先设置,图片加载后,后边的item左右位置错位,可以通过invalidateItemDecorations()更新ItemDecoration,如果不生效,可以尝试view.post(new Runnable())的方式。。
recyclerView.invalidateItemDecorations();
view.post(new Runnable() { @Override public void run() { recyclerView.invalidateItemDecorations(); } });
以上是关于RecyclerView StaggeredGridLayoutManager瀑布流边框刷新问题,错位解决的主要内容,如果未能解决你的问题,请参考以下文章
RecyclerView系列:RecyclerView嵌套RecyclerView(BaseRecyclerViewAdapterHelper实现)