The production of RecyclerView dividing line in Android

When we use RecyclerView to make a list, sometimes we need to use a dividing line. One way is to write the dividing line directly in the item. We introduce another approach here, which is to use the RecyclerView.addItemDecoration method to set the dividing line.

First of all, we need to customize a dividing line class, the code is as follows

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;//上方空白间隔
    }
}

This class sets our blank interval. Then we need to perform some operations.

First, we need to set the background color of the RecyclerView control to the color we need for the dividing line, such as black. Code example:

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

Next we need to set the background color of the item layout file to white. The main reason is that there is a sharp color difference from the background color just set.

<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">

Finally, we call the RecyclerView method in the code to set

recycler.addItemDecoration(new SpacesItemDecoration(1));

The 1 passed in here is the width of the line. In this way, our dividing line is completed.

Guess you like

Origin blog.csdn.net/weixin_38322371/article/details/114891404