The horizontal center of the first RecyclerView item
I want to use RecyclerView
to emulate behavior MultiViewPager
, specifically I would like the selected item to be in the center of the screen including the first and last item .
As you can see in this image, the first element is centered and this will be my expected result.
I installed RecyclerView
with horizontal LinearLayoutManager
and LinearSnapHelper
. The problem with this solution is that the first and last items will never be horizontal as a selection. Should I switch my code to use MultiViewPager
, or is it possible to achieve a similar result using RecyclerView
?
source to share
You can implement this with RecyclerView.ItemDecoration
in getItemOffsets()
to compensate for the first and last elements accordingly.
Get any offsets for this item. Each field
outRect
specifies the number of pixels that the element should look like, such as padding or margin. The default implementation sets the bounds of outRect to 0 and returns.If you need to access the adapter to get more data, you can call
getChildAdapterPosition(View)
to get the position of the adapter in the view.
You may need to use the message size and size and RecyclerView
. But this information can be used in any case.
source to share
The problem with this solution is that the first and last item will never be horizontally centered as a selection.
This is likely due to the fact that your RecycleView is responsible for displaying, within its markup boundaries, exactly the number of items within your dataset.
In the example image below, you can achieve this effect by adding a "placeholder" element at the first and last position of your dataset. This way you can have an invisible element occupying the first slot, thus compensating for the element you want to center.
This placeholder element should not respond to touch events and should not interfere with the processing of click events on other elements (in particular, position processing).
You will need to change your adapters getItemCount
and possibly getItemType
.
source to share