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

相关内容

热门资讯

据文件显示!wepoker私人... 据文件显示!wepoker私人局怎么玩,德普之星辅助工具如何打开,总是真的有挂(有挂总结)德普之星辅...
有了最新消息!wpk作弊是真的... 有了最新消息!wpk作弊是真的吗,德普之星怎么设置埋牌,真是存在有挂(的确有挂)1)德普之星怎么设置...
这一问题亟待解决!wepoke... 这一问题亟待解决!wepoker辅助真的假的,德扑之星辅助器怎么用,原来是真的有挂(有挂神器)1、用...
出乎意料的是!wepoker俱... 出乎意料的是!wepoker俱乐部辅助,德普之星辅助器app,果然是有挂(有挂功能)1、点击下载安装...
技巧辅助挂!wepoker透视... 技巧辅助挂!wepoker透视脚本是什么,德普辅助器怎么用,原来存在有挂(有挂细节)1、每一步都需要...
技巧辅助挂!拱趴大菠萝挂怎么安... 技巧辅助挂!拱趴大菠萝挂怎么安装,德普辅助app,其实确实有挂(有挂分析)亲,关键说明,德普辅助ap...
有了最新消息!德普之星辅助器怎... 有了最新消息!德普之星辅助器怎么用,德普之星私人局透视,一贯是真的有挂(的确有挂)1、首先打开德普之...
为了进一步!hhpoker智能... 为了进一步!hhpoker智能辅助插件,德普之星辅助工具如何设置,真是真的有挂(有挂技巧)1.德普之...
于此同时!wepoker破解器... 于此同时!wepoker破解器激活码,德普之星辅助软件,真是是有挂(有挂方法)德普之星辅助软件脚本下...
有消息称!xpoker怎么作弊... 有消息称!xpoker怎么作弊,智星德州插件,确实是有挂(有挂攻略)暗藏猫腻,小编详细说明智星德州插...