AndroidRecyclerView水平布局中GridLayoutManager存在装饰问题吗?
创始人
2024-10-09 17:32:30
0

问题描述: 在使用RecyclerView实现水平滚动的布局时,如果使用GridLayoutManager并添加了ItemDecoration,则会发现装饰物会错位或缺失。这是由于GridLayoutManager的实现中,对于装饰物的绘制并没有进行完备的处理。

解决步骤: 我们可以通过重写GridLayoutManager的onDraw方法,手动绘制装饰物来解决此问题,代码示例如下:

private final Rect mBounds = new Rect(); //用于存储当前item的位置信息 @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { final int childCount = parent.getChildCount(); final int spanCount = getSpanCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final int position = parent.getChildAdapterPosition(child); if (position < spanCount) { continue; } /** 绘制顶部装饰物 / if (position % spanCount == 0) { mBounds.set(parent.getPaddingLeft(), parent.getPaddingTop(), parent.getWidth() - parent.getPaddingRight(), child.getTop()); drawTop(c, parent, mBounds); } /* 绘制底部装饰物 / drawBottom(c, parent, child, spanCount); /* 绘制item右边装饰物 */ if ((position + 1) % spanCount != 0) { mBounds.set(child.getRight(), child.getTop(), child.getRight() + getDecorationWidth(), child.getBottom()); drawRight(c, parent, mBounds); } } } private void drawTop(Canvas c, RecyclerView parent, Rect bounds) { final Drawable drawable = getTopDecoration(); drawable.setBounds(bounds); drawable.draw(c); } private void drawBottom(Canvas c, RecyclerView parent, View child, int spanCount) { final RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams(); final int position = parent.getChildAdapterPosition(child); final Drawable drawable = getBottomDecoration(); if (position >= spanCount) { mBounds.set(child.getLeft() - layoutParams.leftMargin, child.getTop() - getDecorationWidth(), child.getRight(), child.getTop()); drawable.setBounds(mBounds); drawable.draw(c); } } private void drawRight(Canvas c, RecyclerView parent, Rect bounds) { final Drawable drawable = getRightDecoration(); drawable.setBounds(bounds); drawable.draw(c); }

在此代码中,我们重载了onDraw

相关内容

热门资讯

实操分享!欢乐联盟卡五星辅助,... 实操分享!欢乐联盟卡五星辅助,九酷互娱辅助,系统教程(详细教程)-哔哩哔哩>>您好:软件加薇1367...
必看攻略!欢乐茶馆修改器,九九... 欢乐茶馆修改器是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微信...
攻略讲解!多乐辅助下载,aap... 大家好,今天小编来为大家解答多乐辅助下载这个问题咨询软件客服可以免费测试直接加微信(13670430...
一起来讨论!福建天庭啊开心辅助... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
实测发现!小程序游戏修改器辅助... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
终于知道!创思维激k软件助手,... 终于知道!创思维激k软件助手,衢州都莱辅助软件,解说技巧(有挂细节)-哔哩哔哩【无需打开直接搜索加薇...
交流学习经验!广东雀神麻雀辅助... 交流学习经验!广东雀神麻雀辅助神器,爱来大菠萝怎么玩,新2026教程(有挂透明挂)-哔哩哔哩【无需打...
重大通报!wepoker辅助器... 重大通报!wepoker辅助器,八闽福建辅助,可靠技巧(有挂工具)-哔哩哔哩;无需打开直接搜索打开薇...
盘点一款!边锋小程序辅助免费,... 您好:这款边锋小程序辅助免费游戏是可以开挂的,确实是有挂的,很多玩家在这款边锋小程序辅助免费游戏中打...
实测教程!微乐四川亲友圈辅助器... 实测教程!微乐四川亲友圈辅助器,新天道辅助软件,揭秘攻略(有挂功能)-哔哩哔哩;打开点击测试直接进入...