Horizontally center first item of RecyclerView

亡梦爱人 提交于 2019-12-30 03:21:05

问题


I want to use a RecyclerView to emulate the behavior of a MultiViewPager, in particular I'd like to have the selected item at the center of the screen, including the first and the last element.

As you can see in this image, the first item is centered and this would be my expected result.

What I did was to setup a RecyclerView with an horizontal LinearLayoutManager and a LinearSnapHelper. The problem with this solution is that the first and the last item will never be horizontally centered as selection. Should I switch my code so that it uses a MultiViewPager or is it possible to achieve a similar result taking advantage of a RecyclerView?


回答1:


You can implement this with an RecyclerView.ItemDecoration in getItemOffsets(), to offset the first and last item appropriately.

Retrieve any offsets for the given item. Each field of outRect specifies the number of pixels that the item view should be inset by, similar to padding or margin. The default implementation sets the bounds of outRect to 0 and returns.

If you need to access Adapter for additional data, you can call getChildAdapterPosition(View) to get the adapter position of the View.

You might need to use the messured size of the item and the RecyclerView as well. But these information is available to be used anyhow.




回答2:


The problem with this solution is that the first and the last item will never be horizontally centered as selection.

This is probably because your RecycleView is responsible for showing, within its layout bounds, exactly the number of items that are inside of your data set.

In the example image you provided, you can achieve that effect by adding a "placeholder" item in the first and last position of your dataset. This way, you can have an invisible item taking up the first slot, thus offsetting the item you want to be centered.

This placeholder item should not respond to touch events and should not interfere with handling of click events on other items (specifically, the position handling).

You will have to modify your adapters getItemCount and perhaps getItemType.




回答3:


Just add padding on RecyclerView and add clipToPadding=false and it'll only affect the items on the ends.



来源:https://stackoverflow.com/questions/44662420/horizontally-center-first-item-of-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!