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是不是有人用挂,werplan外卦神器,黑科技教程(有挂攻略)1、不需要AI...
推荐一款!wpk模拟器多开,a... 1、推荐一款!wpk模拟器多开,aa poker辅助包,黑科技教程(有挂辅助);详细教程。2、wpk...
揭秘几款!sohoo竞技联盟辅... 揭秘几款!sohoo竞技联盟辅助器,wejoker辅助软件价格,攻略教程(有挂辅助)关于sohoo竞...
玩家爆料!hhpoker买挂,... 玩家爆料!hhpoker买挂,hhpoker有后台操控吗,微扑克教程(有挂神器);hhpoker有后...
分享个大家!线上德州的辅助器是... 分享个大家!线上德州的辅助器是什么,pokemomo辅助工具,黑科技教程(有挂辅助);原来确实真的有...
详细说明!pokermaste... 详细说明!pokermaster辅助器,wepoker模拟器哪个好用,透明教程(有挂教程)是由北京得...
科技通报!德州局透视脚本下载安... 科技通报!德州局透视脚本下载安装最新版本,德州透视hhpoker,揭秘教程(有挂技巧)准备好在德州局...
专业讨论!wepoker辅助器... 专业讨论!wepoker辅助器如何使用,德扑HHpoker有挂吗,2025新版教程(有挂教程);大神...
玩家必看教程!佛手大菠萝有挂吗... 玩家必看教程!佛手大菠萝有挂吗,德普之星透视辅助,wpk教程(有挂技巧)是一款可以让一直输的玩家,快...
实测发现!约局吧辅助器,哈糖大... 实测发现!约局吧辅助器,哈糖大菠萝万能挂,教你教程(有挂攻略);《WPK辅助透视》‌:支持手机实时对...