RecyclerView remove divider / decorator after the last item

前端 未结 9 2078
礼貌的吻别
礼貌的吻别 2020-12-07 17:46

I have a quite simple RecyclerView.
This is how I set the divider:

DividerItemDecoration itemDecorator = new DividerItemDecoration(getContext(), DividerI         


        
9条回答
  •  独厮守ぢ
    2020-12-07 18:01

    If you don't like divider being drawn behind, you can simply copy or extend DividerItemDecoration class and change its drawing behaviour by modifying for (int i = 0; i < childCount; i++) to for (int i = 0; i < childCount - 1; i++)

    Then add your decorator as recyclerView.addItemDecoration(your_decorator);

    Previous solution

    As proposed here you can extend DividerItemDecoration like this:

    recyclerView.addItemDecoration(
        new DividerItemDecoration(context, linearLayoutManager.getOrientation()) {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = parent.getChildAdapterPosition(view);
                // hide the divider for the last child
                if (position == state.getItemCount() - 1) {
                    outRect.setEmpty();
                } else {
                    super.getItemOffsets(outRect, view, parent, state);
                }
            }
        }
    );
    

    @Rebecca Hsieh pointed out:

    This works when your item view in RecyclerView doesn't have a transparent background, for example,

    
        ... 
    
    

    DividerItemDecoration.getItemOffsets is called by RecyclerView to measure the child position. This solution will put the last divider behind the last item. Therefore the item view in RecyclerView should have a background to cover the last divider and this makes it look like hidden.

提交回复
热议问题