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(); } });
本文来自博客园,作者:西瓜皮不甜,转载请注明原文链接:https://www.cnblogs.com/Jieth/p/13098560.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库