安卓RecyclerView简单快速添加自定义宽度和颜色的分割线

效果图在这里插入图片描述
在这里插入图片描述

Step1. 编写activity_main.laylout
首先,在主布局中添加Recyclerview,设置背景色,这个就是分割线的颜色

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff888888"
    />
</LinearLayout>

Step2. item_text.laylout
这里新建了一个简单的TextView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/item_tx"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:gravity="center"
        android:layout_gravity="center_horizontal"
        />

</LinearLayout>

Step3.主活动编写recyclerView.AddItemDecoration方法,重写getItemOffsets方法,outRect.set(0,0,0,3);设置bottom偏移宽度,就是分割线的宽度

@Override
           public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(0,0,0,10);//分割线宽度
            }

            @Override
            public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
                Paint paint=new Paint();
                paint.setColor(Color.WHITE);//列表TextView的颜色
                int count=parent.getChildCount();//获取列表数量
                for(int i=0;i<count;i++){
                    final View child=parent.getChildAt(i);
                    //最后一个底下不需要分割线
                    if(i==count-1){
                        c.drawRect(child.getLeft(), child.getTop(),child.getRight(),
                                child.getBottom()+10,paint);
                    }
                    else {
                        c.drawRect(child.getLeft(), child.getTop(),child.getRight(),
                                child.getBottom(),paint);
                    }
                }
            }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值