ItemDecoration

建立類別繼承RecyclerView.ItemDecoration,有三個可覆寫的方法。
  • getItemOffsets:分隔,使用outRect.set方法繪製類似margin效果。
  • onDrawOver:在子項目繪製後繪製。
  • onDraw:在子項目繪製前繪製。
建構式
//索引的主題android.R.attr.listDivider,支持垂直、平行。
public ItemDecoration(Context context, AttributeSet attrs) {
        mTypedArray = context.obtainStyledAttributes(
                                        attrs, new int[]{android.R.attr.listDivider});
        mDrawable = mTypedArray.getDrawable(0);        
        mTypedArray.recycle();
}
getItemOffsets
 @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        if (mDrawable == null) {
            return;
        }

        if (parent.getChildAdapterPosition(view) < 0) {
            return;
        }

        mLayoutManager = parent.getLayoutManager();
        //目前獲取到的項目
        mItemPosition = parent.getChildAdapterPosition(view);  
        //獲取列表的總數
        mItemCount = state.getItemCount();     

        if (parent.getLayoutManager() instanceof GridLayoutManager 
                  || parent.getLayoutManager() instanceof StaggeredGridLayoutManager) {
            mSpanCount = ((GridLayoutManager) layoutManager).getSpanCount();
            //判斷最後一行
            outRect.set( 0, 0, 0, itemPosition >= (itemCount - itemCount % spanCount) ? 20: 0);
        }else{
             outRect.set(20, 20, 20, 20);   
        }

    }
onDrawOver
@Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {

        if (mDrawable == null) {
            super.onDrawOver(c, parent, state);
            return;
        }

        mOrientation = getOrientation(parent);
        mChildCount = parent.getChildCount();

        if (mOrientation == LinearLayoutManager.VERTICAL) {
            mSize = mDrawable.getIntrinsicHeight();
            mLeft = parent.getPaddingLeft();
            mRight = parent.getWidth() - parent.getPaddingRight();
        } else { 
            mSize = mDrawable.getIntrinsicWidth();
            mTop = parent.getPaddingTop();
            mBottom = parent.getHeight() - parent.getPaddingBottom();
        }

        for (int i =1; i < mChildCount; i++) {
            mChildView = parent.getChildAt(i);
            mParams = (RecyclerView.LayoutParams) mChildView.getLayoutParams();

            if (mOrientation == LinearLayoutManager.VERTICAL) {
                mTop = mChildView.getTop() - mParams.topMargin;
                mBottom = mTop + mSize;
            } else { 
                mLeft = mChildView.getLeft() - mParams.leftMargin;
                mRight = mLeft + mSize;
            }

            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setColor(Color.BLUE);
            c.drawRect(left, top, right, bottom, mPaint);
        }
    }