LinearSnapHelper does not bind to red items of RecyclerView

This is a follow-up to my previous question .

In my application, I am trying to create a horizontal RecyclerView

one that automatically snaps to the center item. For this I tied to it LinearSnapHelper

. I also created an element decoration that adds some left / right padding to the first / last element:

public class OffsetItemDecoration extends RecyclerView.ItemDecoration {

    private Context ctx;

    public OffsetItemDecoration(Context ctx){
        this.ctx = ctx;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int nCols = ActivityUtils.getNumCols(ctx);
        int colWidth = (int)(getScreenWidth()/(float)(nCols));

        if(parent.getChildAdapterPosition(view) == 0){
            int offset = Math.round(getScreenWidth() / 2f - colWidth / 2f);
            setupOutRect(outRect, offset, true);
        }

        else if (parent.getChildAdapterPosition(view) == state.getItemCount()-1){
            int offset = Math.round(getScreenWidth() / 2f - colWidth / 2f);
            setupOutRect(outRect, offset, false);
        }
    }

    private void setupOutRect(Rect rect, int offset, boolean start){
        if(start) rect.left = offset;
        else rect.right = offset;
    }

    private  int getScreenWidth(){
        WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size.x;
    }
}

      

The problem is that on first fill, the RecyclerView

first element is centered on the screen and also selected, but when I try to scroll horizontally and I go back to the first element, the leftmost element I can select the second (position 1

). The same happens for the last element, the rightmost element that can be anchored is the penultimate one. ( state.getItemCount() - 2

).

Do I need to implement a new one SnapHelper

, or am I doing something wrong?

+5


source to share


1 answer


RecyclerView

has its own rules about ItemDecoration

. He thinks of them as part of the subject itself. You may think that yours decoration

(even if only padding

) is part of yours my_item.xml

.



LinearSnapHelper

uses type methods LayoutManager.getDecoratedMeasuredWidth()

to determine the center of the view. And that's where the problem comes from. It sees that your first element is much larger than you think, so it centers for the first view at (padding + view.getWidth()) / 2

. This is much further than the center of the second view, which is normal view.getX() + view.getWidth() / 2

.

+3


source







All Articles