将RecyclerView的第一项水平居中 [英] Horizontally center first item of RecyclerView

查看:794
本文介绍了将RecyclerView的第一项水平居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用RecyclerView来模仿MultiViewPager的行为,特别是我想将所选项目放在屏幕中央,包括第一个和最后一个元素.

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.

我要做的是设置一个带有水平LinearLayoutManagerLinearSnapHelperRecyclerView.该解决方案的问题在于,第一项和最后一项将永远不会在选择时水平居中.我应该切换代码以使其使用MultiViewPager还是可以利用RecyclerView获得类似的结果?

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?

推荐答案

您可以在 getItemOffsets() ,以适当地抵消第一项和最后一项.

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

检索给定项目的所有偏移量. outRect的每个字段指定插入项目视图的像素数,类似于填充或边距.默认实现将outRect的边界设置为0并返回.

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.

您可能需要使用项目的混乱大小以及RecyclerView.但是这些信息仍然可以使用.

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.

这篇关于将RecyclerView的第一项水平居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆