简单有效的ItemDecoration--分割线

1、ItemDecoration

class ItemDecoration extends RecyclerView.ItemDecoration {
        private Drawable mDivider;
    
        public ItemDecoration(Drawable divider) {
            mDivider = divider;
        }
        
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
        
            if (parent.getChildAdapterPosition(view) == 0) {
                return;
            }
        
            outRect.top = mDivider.getIntrinsicHeight();
        }
    
        @Override
        public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
            int dividerLeft = parent.getPaddingLeft();
            int dividerRight = parent.getWidth() - parent.getPaddingRight();
        
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount - 1; i++) {
                View child = parent.getChildAt(i);
            
                RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            
                int dividerTop = child.getBottom() + params.bottomMargin;
                int dividerBottom = dividerTop + mDivider.getIntrinsicHeight();
            
                mDivider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom);
                mDivider.draw(canvas);
            }
        }
    }

2、divider drawable

如果想更改分割线颜色和宽度在下面改


<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <size android:height="1px" />
    <solid android:color="#888" />
shape>

3、使用代码

Drawable drawable = mContext.getDrawable(R.drawable.divider);
mRecyclerView.addItemDecoration(new ItemDecoration(drawable));

你可能感兴趣的:(android)