2

我正在使用无限滚动的循环器视图,其中包含重复的 X 项。我也想使用PagerSnapHelper()像 viewpager 一样捕捉滚动。

所以最初加载列表时,显示就像 - 在此处输入图像描述

一旦我开始在左右两侧滚动,PageSnapHelper() 就会开始工作,就像 viewpager 一样,中心对齐是这样的 -在此处输入图像描述

我想在最初加载时将 recyclerview 显示为第二张图像。请告诉接下来要做什么来实现这一目标。

这是代码片段 -

linearLayoutManager = new LinearLayoutManager(mContext,   LinearLayoutManager.HORIZONTAL, false);
this.recyclerView.setLayoutManager(linearLayoutManager);
SnapHelper snapHelper = new PagerSnapHelper();
adapterCarousel = new AdapterCarousel(mContext, glideRequestManager);
adapterCarousel.setViewType(RECYCLER_VIEW_TYPE_NORMAL);
adapterCarousel.setCarousel(carousel);
this.recyclerView.setAdapter(adapterCarousel);
snapHelper.attachToRecyclerView(recyclerView);
linearLayoutManager.scrollToPosition(Integer.MAX_VALUE / 2);
4

3 回答 3

2

我通过使用解决了这个问题LinearLayoutManager#scrollToPositionWithOffset(pos, offset)。我只是将滚动位置偏移了项目之间填充的一半。这对我有用,因为我的项目与屏幕的宽度相同。在您的情况下,您需要做一些数学运算。

假设您的项目的宽度是W,您的 RecyclerView 具有宽度rvW,并且项目之间的填充是padding您想要抵消的数量由(rvW - W)/2 - padding/2or给出(rvW - W - padding)/2

最终代码:

// post to give the recyclerview time to layout so it's width isn't 0
mRecyclerView.post(new Runnable() {
    void run() {
        int padding = getResources().getDimensionPixelSize(R.dimen.some_padding);
        int rvWidth = mRecyclerView.getWidth();
        int itemWidth = getResources().getDimensionPixelSize(R.dimen.itemWidth);
        int offset = (rvWidth - itemWidth - padding) / 2;
        mLinearLayoutManager.scrollToPositionWithOffset(pos, offset);
    }
});

对代码的一些可选改进:

  • 如果您确定 RecyclerView 将始终适合屏幕的宽度,则可以使用甚至显示的宽度View#measure(),而不是发布到 RecyclerView 。View#getMeasuredWidth()

  • 如果您的 RecyclerView 的孩子是可变大小的,您可以通过获取视图mLinearLayoutManager.findViewByPosition(mLinearLayoutManager.findFirstVisibleItemPosition())并以这种方式获取它的宽度。

于 2018-02-14T01:52:39.950 回答
0

对我来说使用recyclerView.smoothScrollToPosition(x);而不是linearLayoutManager.scrollToPosition(x);成功

于 2017-03-29T11:07:30.590 回答
0
   linearLayoutManager.scrollToPosition((Integer.MAX_VALUE / 2)-1);
   linearLayoutManager.smoothScrollToPosition(Integer.MAX_VALUE / 2);

如果有更好的方法请告诉我

于 2017-03-31T09:28:28.907 回答