0

我正在为一个学校项目编写一个 Android 应用程序。

我已经RecyclerView使用LinearLayoutManager.HORIZONTAL.

我想让一个特定的元素,例如元素 n,位于当前可见元素集 的中间,如下所示:在此处输入图像描述

我四处搜索,发现了这个链接:https ://www.reddit.com/r/androiddev/comments/3o0xzw/how_do_you_scroll_to_an_item_with_recyclerview_to/

解决方案涉及取一半的总和layoutManager.findFirstVisibleItemPosition()并将layoutManager.findLastVisibleItemPosition()其添加到您想要位于中间的元素的位置。

RecyclerView.NO_POSITION但是,当我使用这个水平滚动时,这两个方法总是返回RecyclerView,因此总和的一半是 0,它会使计算变得无用。

这是我的代码:

RecyclerView selectDay = (RecyclerView) findViewById(R.id.lv_selectDay);
    daySelectorAdapter adapter = new daySelectorAdapter(this, arrayList);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    selectDay.setAdapter(adapter);
    selectDay.setLayoutManager(layoutManager);

    int firstVisible = layoutManager.findFirstVisibleItemPosition();
    Log.d("FIRSTVISIBLE", String.valueOf(firstVisible)); // returns -1

    int lastVisible = layoutManager.findLastVisibleItemPosition();
    Log.d("LASTVISIBLE", String.valueOf(lastVisible)); // also -1

    int halfScreenOffset = (lastVisible - firstVisible) / 2;
    Log.d("HALFOFFSET", String.valueOf(halfScreenOffset));

    layoutManager.scrollToPositionWithOffset((15 + halfScreenOffset), 0);

我可以知道是否有人有解决此问题的方法吗?提前致谢。

编辑:当我尝试实现 aonScrollListener和 cast recyclerView.getLayoutManager()to 时LinearLayoutManager,这些方法工作得很好。我可以知道为什么吗?

编辑2:

我在这里使用了这个解决方案:RecyclerView smoothScroll to position in the center。android,但是为什么方法会返回NO_POSITION

4

0 回答 0