How to add dividers and spaces between items in RecyclerView?

前端 未结 30 2888
清歌不尽
清歌不尽 2020-11-22 03:27

This is an example of how it could have been done previously in the ListView class, using the divider and dividerHeight parame

30条回答
  •  臣服心动
    2020-11-22 04:11

    I think using simple divider will help you

    To add divider to each item:
    1- Add this to drawable directory line_divider.xml

    
    
    
    
    
    

    2- Create SimpleDividerItemDecoration class
    I used this example to define this class:
    https://gist.github.com/polbins/e37206fbc444207c0e92

    package com.example.myapp;
    import android.content.Context;
    import android.content.res.Resources;
    import android.graphics.Canvas;
    import android.graphics.drawable.Drawable;
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import com.example.myapp.R;
    
    public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration{
    private Drawable mDivider;
    
    public SimpleDividerItemDecoration(Resources resources) {
        mDivider = resources.getDrawable(R.drawable.line_divider);
    }
    
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        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);
        }
      }
    }
    


    3- In activity or fragment that using RecyclerView, inside onCreateView add this:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
     RecyclerView myRecyclerView = (RecyclerView) layout.findViewById(R.id.my_recycler_view);
     myRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));
     ....
     }
    


    4- To add spacing between Items
    you just need to add padding property to your item view

    
    ..... item structure
    
    

提交回复
热议问题