1. 程式人生 > >RecyclerView列表呼叫addItemDecoration實現新增自定義分割線

RecyclerView列表呼叫addItemDecoration實現新增自定義分割線

RecyclerView不像ListView那樣自帶分割線,需要自定義分割線

先在drawable中建立一個line_divider.xml檔案使用者設定分割線的顏色

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <size
        android:width="1dp"
        android:height="1dp" />
    <solid android:color="#84625d5d" />
自定義RecyclerView.ItemDecoration類的子類SimpleDividerItemDecoration類,程式碼如下:
public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;     //分割線Drawable
    private int mDividerHeight;  //分割線高度

    /**
     * 使用line_divider中定義好的顏色
     *
     * @param context
 * @param dividerHeight 分割線高度
 */
public SimpleDividerItemDecoration(Context context, int dividerHeight) {
    mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);
    mDividerHeight = dividerHeight;
}

/**
 * @param context
 * @param divider       分割線Drawable
 * @param dividerHeight 分割線高度
 */
public SimpleDividerItemDecoration(Context context, Drawable divider, int dividerHeight) {
    if (divider == null) {
        mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);
    } else {
        mDivider = divider;
    }
    mDividerHeight = dividerHeight;
}

//獲取分割線尺寸
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);
    outRect.set(0, 0, 0, mDividerHeight);
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
    int left = parent.getPaddingLeft();
    int right = parent.getWidth() - parent.getPaddingRight();

    int childCount = parent.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = parent.getChildAt(i);

        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

        int top = child.getBottom() + params.bottomMargin;
        int bottom = top + mDividerHeight;
        mDivider.setBounds(left, top, right, bottom);
        mDivider.draw(c);
    }
}

} 使用:

recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this,drawable, 5));