【问题标题】:RecyclerView in setReverseLayout scroll to top (or bottom)setReverseLayout 中的 RecyclerView 滚动到顶部(或底部)
【发布时间】:2017-02-12 12:46:40
【问题描述】:

对于可能具有误导性的标题,我深表歉意,但我不知道如何措辞。如果其他人认为他们可以提出更好的建议,请随时编辑。

我有一个用 Firebase 记录填充的 RecyclerView。为了使最近的记录显示在列表的顶部,我将我的 RecvlerView 设置为 setReverseLayout(true) 和 setStackFromEnd(true),如建议的 here。当项目数量适合屏幕空间时,这非常有用 - 其余项目平滑向下滚动,为淡入的新项目留出空间,如下所示。

问题是当现有项目占据所有屏幕空间时,新项目被添加到其他项目的“上方”并且 RecyclerView 有效地扩展至屏幕顶部上方,所以要查看新项目我需要拉或手动向下滚动列表。下面是另一个 GIF;

我该如何克服这个问题?

【问题讨论】:

  • 你能分享这个示例链接吗...这很有用
  • @GunduBandagar 抱歉,你要分享什么链接?
  • 你做上面的代码,我想要这个老板.. :)

标签: android android-recyclerview


【解决方案1】:
final int SCROLLING_UP = -1;
boolean scrollToNewTop = !recyclerView.canScrollVertically(SCROLLING_UP);
//TODO update adapter here
adapter.notifyItemInserted(adapter.getItemCount() - 1);
if (scrollToNewTop) {
    recyclerView.scrollToPosition(adapter.getItemCount() - 1);
}

如果您位于最顶端,这将向上滚动您,如果您处于中间位置,则一切都保持原样,以免烦人的跳跃。

【讨论】:

    【解决方案2】:

    这可能会有所帮助:

    adapter.notifyItemInserted(position);
    recyclerView.scrollToPosition(position);
    

    【讨论】:

      【解决方案3】:
        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
              @Override
              public void onItemRangeInserted(int positionStart, int itemCount) {
                  super.onItemRangeInserted(positionStart, itemCount);
                  int testimonycount = mAdapter.getItemCount();
                  int lastVisiblePosition =
                          linearLayoutManager.findLastCompletelyVisibleItemPosition();
                  // If the recycler view is initially being loaded or the
                  // user is at the bottom of the list, scroll to the bottom
                  // of the list to show the newly added message.
                  if (lastVisiblePosition == -1 ||
                          (positionStart >= (testimonycount - 1) &&
                                  lastVisiblePosition == (positionStart - 1))) {
                      recipeRecyclerview.scrollToPosition(positionStart);
                  }
              }
      

      【讨论】:

      • 欢迎来到 Stackoverflow。最好在您的答案中添加一些描述,以显示您提出的代码如何解决问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多