Add margins to divider in RecyclerView

后端 未结 8 942
深忆病人
深忆病人 2020-12-14 01:11

i am building an android app which is using RecyclerView. I want to add dividers to RecyclerView, which I did using this code:

Divi         


        
8条回答
  •  孤街浪徒
    2020-12-14 01:27

    Below is the code for divider in RecyclerView with left margin. Just paste the code in your OnCreate method of MainActivity.

    class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
        private Drawable mDivider;
    
        public SimpleDividerItemDecoration(Context context) {
            mDivider = context.getResources().getDrawable(R.drawable.divider);
        }
    
        @Override
        public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
            int left = 250;
            int right = parent.getWidth() - parent.getPaddingRight();
    
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = parent.getChildAt(i);
    
                RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
    
                int top = child.getBottom() + params.bottomMargin;
                int bottom = top + mDivider.getIntrinsicHeight();
    
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    }
    
    recyclerView.addItemDecoration(new SimpleDividerItemDecoration(
                getApplicationContext()));
    

    Since, the divider.xml file will be missing from your drawable folder so below is the code that you have to paste on the divider layout after creating it on drawable folder.

    
    
    
      
    
      
    
    
    

提交回复
热议问题