RecyclerVieW自定義華麗的分割線

i風發表於2017-09-18

RecyclerView因沒有自帶分割線所以需要我們自定義分割線,在這裡提供了一個簡單的實現分割線的方法
程式碼如下:

public class ItemDecoration extends RecyclerView.ItemDecoration{
    private int mydevider;
    private Paint dividerPaint;

    public ItemDecoration(Context context) {
        dividerPaint = new Paint();
        //設定分割線顏色
        dividerPaint.setColor(context.getResources().getColor(R.color.colorAccent));
        //設定分割線寬度
        mydevider = context.getResources().getDimensionPixelSize(R.dimen.divider_bottom);

    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.bottom = mydevider;
    }

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

        for (int i = 0; i < childCount - 1; i++) {
            View view = parent.getChildAt(i);
            float top = view.getBottom();
            float bottom = view.getBottom() + mydevider;
            c.drawRect(left, top, right, bottom, dividerPaint);
        }
    }
}

首先我們需要建立一個類來繼承RecyclerView.ItemDecoration這個抽象方法,
接下來就是在Activity中例項化這個類傳入一個當前物件即可;
再用RecyclerView控制元件呼叫addItemDecoration()這個方法傳入剛定義的類物件即可實現自定義分割線;
Activity類

   ItemDecoration itemDecoration=new ItemDecoration(MainActivity.this);
   recyclerView.addItemDecoration(itemDecoration);

設定分割線的寬度是用到了一個dimen,只需要在res/values下新建一個dimen即可;
程式碼如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="divider_bottom">1dp</dimen>

</resources>

至此分割線就可以實現了= =

相關文章