Android中RecyclerView分割线的制作

当我们使用RecyclerView制作列表的时候,有时候需要用到分割线。一种做法是把分割线直接写在item中。我们在这里介绍另一种做法,那就是使用RecyclerView.addItemDecoration方法设置分割线。

首先我们需要自定义一个分割线的类,代码如下

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

    private int space;//空白间隔

    public SpacesItemDecoration(int space){
        this.space = space;
    }

    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,RecyclerView.State state){
        outRect.left = space;//左边空白间隔
        outRect.right = space;//右边空白间隔
        outRect.bottom = space;//下方空白间隔
        outRect.top = space;//上方空白间隔
    }
}

这个类设置的是我们的空白间隔。接着我们需要进行一些操作。

首先我们要将RecyclerView控件的背景色设置为我们分割线需要的颜色,比如黑色,代码示例:

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:background="#000000"/>

接着我们要把项布局文件的背景色设置为白色。主要是和刚才设置的背景色要有鲜明色差。

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

最后我们在代码中调用RecyclerView的方法进行设置

recycler.addItemDecoration(new SpacesItemDecoration(1));

这里传入的1就是线的宽度。这样我们的分割线就制作完成了。

猜你喜欢

转载自blog.csdn.net/weixin_38322371/article/details/114891404