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

相关内容

热门资讯

每日必看教程透视挂!年年大厅透... 每日必看教程透视挂!年年大厅透视挂多功能AI插件,年年大厅一直真的有透视挂插件1、操作简单,无需年年...
今日头条外挂!王者众娱外挂多功... 今日头条外挂!王者众娱外挂多功能AI插件,王者众娱竟然存在有外挂插件进入游戏-大厅左侧-新手福利-激...
必备科技作弊器!淮滨互娱作弊器... 必备科技作弊器!淮滨互娱作弊器多功能AI工具,淮滨互娱真是真的是有作弊器工具1、进入到淮滨互娱是否有...
我来分享作弊器!本地互娱作弊器... 我来分享作弊器!本地互娱作弊器多功能AI技巧,本地互娱本来是有作弊器技巧本地互娱透视方法中分为三种模...
终于懂了作弊器!众享互娱作弊器... 终于懂了作弊器!众享互娱作弊器多功能AI方法,众享互娱好像存在有作弊器方法运众享互娱辅助工具,进入游...
带你了解透视挂!葫芦娃大厅透视... 带你了解透视挂!葫芦娃大厅透视挂多功能AIapp,葫芦娃大厅好像存在有透视挂app1、该软件可以轻松...
让我来分享经验透视挂!欢盈娱乐... 让我来分享经验透视挂!欢盈娱乐透视挂多功能AI软件,欢盈娱乐本来真的有透视挂软件1、玩家可以在欢盈娱...
技术分享辅助器!海象互娱辅助器... 技术分享辅助器!海象互娱辅助器多功能AI工具,海象互娱好像有辅助器工具1、下载好海象互娱脚本下载之后...
科普攻略辅助!福城娱乐辅助多功... 科普攻略辅助!福城娱乐辅助多功能AI插件,福城娱乐真是存在有辅助插件1、福城娱乐破解器简单,福城娱乐...
查到实测开挂!红月大厅开挂多功... 查到实测开挂!红月大厅开挂多功能AI方法,红月大厅确实是真的有开挂方法1、玩家可以在红月大厅透视最简...