Android recyclerview gridLayoutManager的分割线Decoration

您所在的位置:网站首页 纵向分割线 Android recyclerview gridLayoutManager的分割线Decoration

Android recyclerview gridLayoutManager的分割线Decoration

2024-07-11 19:42| 来源: 网络整理| 查看: 265

最近用到了  需要九宫格的上下左右都有分割  于是上网找了好几个  有一个用着还不错  自己改了一下  在此记录  

这个方法我尝试了三四次   刚开始  总是有问题  不是第一列间距小了  就是没有间距了   然后又换方法  最后又换了回来   发现是我的adapter里面的item 宽度设置有问题   因为使用的是GridLayoutManager   他是根据设置列数   然后等分的   我开始把item的宽度写死xxdp了  然后就出现某一列的间距有问题   这里面item的宽度要设置成match_parent   就可以了    

全部代码  getItemOffsets里面的代码可以根据需求动态修改

import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Created by admin on 2019/10/9. */ public class MyItemDecoration extends RecyclerView.ItemDecoration { private int space; private int color; private Paint mPaint; /** * 默认的,垂直方向 横纵1px 的分割线 颜色透明 */ public MyItemDecoration() { this(1); } /** * 自定义宽度的透明分割线 * * @param space 指定宽度 */ public MyItemDecoration(int space) { this(space, Color.TRANSPARENT); } /** * 自定义宽度,并指定颜色的分割线 * * @param space 指定宽度 * @param color 指定颜色 */ public MyItemDecoration(int space, int color) { this.space = space; this.color = color; initPaint(); } private void initPaint() { mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setColor(color); mPaint.setStyle(Paint.Style.FILL); mPaint.setStrokeWidth(space); } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { GridLayoutManager manager = (GridLayoutManager) parent.getLayoutManager(); int childSize = parent.getChildCount(); int span = manager.getSpanCount(); //为了Item大小均匀,将设定分割线平均分给左右两边Item各一半 int offset = space / 2; //得到View的位置 int childPosition = parent.getChildAdapterPosition(view); //第一排,顶部 if (childPosition < span) { //最左边的 if (childPosition % span == 0) { outRect.set(space, space, offset, 0); //最右边的 } else if (childPosition % span == span - 1) { outRect.set(offset, space, space, 0); //中间的 } else { outRect.set(offset, space, offset, 0); } } else { //上下的分割线,就从第二排开始 //最左边的 if (childPosition % span == 0) { outRect.set(space, space, offset, 0); //最右边的 } else if (childPosition % span == span - 1) { outRect.set(offset, space, space, 0); //中间的 } else { outRect.set(offset, space, offset, 0); } } } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); } }

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3