【问题标题】:Snap Recyclerview item to Center when loaded加载时将 Recyclerview 项目对齐到中心
【发布时间】:2017-08-22 20:05:33
【问题描述】:

我正在使用无限滚动的循环视图,其中包含重复的 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);

【问题讨论】:

  • 你找到这个问题的答案了吗?

标签: android android-recyclerview horizontal-scrolling linearlayoutmanager


【解决方案1】:

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

假设您的项目的宽度为W,您的 RecyclerView 的宽度为rvW,项目之间的填充为padding,那么您要抵消的数量由(rvW - W)/2 - padding/2(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);
    }
});

对代码的一些可选改进:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这对我不起作用,因为我的列表是无限的,最大大小Integer.Max_Value
    【解决方案3】:
       linearLayoutManager.scrollToPosition((Integer.MAX_VALUE / 2)-1);
       linearLayoutManager.smoothScrollToPosition(Integer.MAX_VALUE / 2);
    

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

    【讨论】:

    • 当我这样做时,当活动/片段首次加载时会出现非常明显的混蛋动画,这是不受欢迎的。
    猜你喜欢
    • 2012-01-08
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多