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

相关内容

热门资讯

必备教程!潮友会辅助器,途游辅... 必备教程!潮友会辅助器,途游辅助软件网站,教会开挂辅助教程(存在有挂)1、下载安装好途游辅助软件网站...
必知教程!悠闲川南游戏辅助,新... 必知教程!悠闲川南游戏辅助,新天道挂机辅助,分析开挂辅助教程(新版有挂)1、下载安装好悠闲川南游戏辅...
热点推荐!小唐家乐园山西辅助软... 热点推荐!小唐家乐园山西辅助软件,广西友乐辅助器,通报开挂辅助教程(有挂教程);无需打开直接搜索打开...
六分钟了解!微信小程序微乐辅助... 六分钟了解!微信小程序微乐辅助器免费下载,开心泉州作弊,传授开挂辅助教程(证实有挂);无需打开直接搜...
一分钟了解!新玉海楼游戏茶苑,... 一分钟了解!新玉海楼游戏茶苑,牵手辅助神器下载,推荐开挂辅助教程(有挂透视);无需打开直接搜索打开薇...
技巧知识分享!h5游戏辅助修改... 技巧知识分享!h5游戏辅助修改器,兴动游戏辅助,正品开挂辅助教程(有挂功能)1、下载安装好h5游戏辅...
今日焦点!金手指辅助工具,人海... 今日焦点!金手指辅助工具,人海大厅反杀,盘点开挂辅助教程(的确有挂)1、下载安装好金手指辅助工具,进...
终于懂了!微信微乐小程序辅助软... 终于懂了!微信微乐小程序辅助软件,樱花之盛辅助软件下载,分享开挂辅助教程(有挂解惑);无需打开直接搜...
记者揭秘!小程序牵手跑得辅助,... 您好:小程序牵手跑得辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的...
大家学习交流!浙江游戏大厅模拟... 大家学习交流!浙江游戏大厅模拟器,山西扣点免费辅助,分析开挂辅助教程(有挂解密);无需打开直接搜索加...