RecyclerView列表調用addItemDecoration實現添加自定義分割線

若是還不會使用RecyclerView,請看個人另外一篇博客java

Android滾動組件RecyclerView 的用法

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

先在drawable中建立一個line_divider.xml文件用戶設置分割線的顏色ide

<?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" />
    
</shape>

自定義RecyclerView.ItemDecoration類的子類SimpleDividerItemDecoration類,代碼以下:this

public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;     //分割線Drawable
    private int mDividerHeight;  //分割線高度
    private int inset;       //分割線縮進值

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

    public SimpleDividerItemDecoration(Context context, int inset, int dividerHeight) {
        this.inset = inset;
        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();
        //最後一個item不畫分割線
        for (int i = 0; i < childCount - 1; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            int top = child.getBottom() + params.bottomMargin;
//            int bottom = top + mDividerHeight;
            int bottom = top + mDivider.getIntrinsicHeight();
            if (inset > 0) {
                mDivider.setBounds(left + inset, top, right - inset, bottom);
            } else {
                mDivider.setBounds(left, top, right, bottom);
            }
            mDivider.draw(c);
        }
    }

}

使用:spa

recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this,20, 5));
相關文章
相關標籤/搜索