1 분 동안 RecyclerView 분할 선 추가

기초 지식http://blog.csdn.net/lmj623565791/article/details/45059587 1 분 에 3 단계 추가
  • RecycleView Divider 류 추가
  • divider. xml 추가
  • 메 인 프로그램 에서 코드 한 줄 쓰기
  • RecycleView Divider 클래스
    public class RecycleViewDivider extends RecyclerView.ItemDecoration {
        private Drawable mDivider;
        private int mDividerHeight = 1;//     ,   1px
        private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    
        /**
         *       
         *
         * @param context
         * @param dividerHeight      
         * @param drawableId         
         */
        public RecycleViewDivider(Context context, int dividerHeight, int drawableId) {
            final TypedArray a = context.obtainStyledAttributes(ATTRS);
            mDivider = a.getDrawable(0);
            a.recycle();
            mDivider = ContextCompat.getDrawable(context, drawableId);
            mDividerHeight = dividerHeight;
        }
    
        //       
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.set(0, 0, 0, mDividerHeight);
        }
        //     
        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            drawDecoration(c, parent);
        }
        //     item    
        private void drawDecoration(Canvas canvas, RecyclerView parent) {
            final int left = parent.getPaddingLeft();
            final int right = parent.getWidth() - parent.getPaddingRight();
            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                final View child = parent.getChildAt(i);
                final RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
                final int top = child.getBottom() + layoutParams.bottomMargin;
                final int bottom = top + mDividerHeight;
                if (mDivider != null) {
                    mDivider.setBounds(left, top, right, bottom);
                    mDivider.draw(canvas);
                }
            }
        }
    }
    

    divider.xml
    
    
        
    
    

    주 프로그램 코드
    mRecyclerView.addItemDecoration(new RecycleViewDivider(
                    getActivity(),2,R.drawable.divider));
    

    좋은 웹페이지 즐겨찾기