How to save scroll position of RecyclerView in Android?

后端 未结 8 1344
耶瑟儿~
耶瑟儿~ 2020-11-27 06:20

I have Recycler view which lays inside of SwipeRefreshLayout. Also, have ability to open each item in another activity. After returning back to Recycler I need scroll to cho

相关标签:
8条回答
  • 2020-11-27 07:05

    Beginning from version 1.2.0-alpha02 of androidx recyclerView library, it is now automatically managed. Just add it with:

    implementation "androidx.recyclerview:recyclerview:1.2.0-alpha02"
    

    And use:

    adapter.stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY
    

    The StateRestorationPolicy enum has 3 options:

    • ALLOW — the default state, that restores the RecyclerView state immediately, in the next layout pass
    • PREVENT_WHEN_EMPTY — restores the RecyclerView state only when the adapter is not empty (adapter.getItemCount() > 0). If your data is loaded async, the RecyclerView waits until data is loaded and only then the state is restored. If you have default items, like headers or load progress indicators as part of your Adapter, then you should use the PREVENT option, unless the default items are added using MergeAdapter. MergeAdapter waits for all of its adapters to be ready and only then it restores the state.
    • PREVENT — all state restoration is deferred until you set ALLOW or PREVENT_WHEN_EMPTY.

    Note that at the time of this answer, recyclerView library is still in alpha03, but alpha phase is not suitable for production purposes.

    0 讨论(0)
  • 2020-11-27 07:05

    You can use scrollToPosition or smoothScrollToPosition to scroll to any item position in RecyclerView.

    If you want to scroll to item position in adapter, then you would have to use adapter's scrollToPosition or smoothScrollToPosition.

    0 讨论(0)
提交回复
热议问题