How to save scroll position of RecyclerView in Android?

后端 未结 8 1396
耶瑟儿~
耶瑟儿~ 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 06:51

    to save position to Preferences, add this to your onStop()

     int currentVisiblePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
     getPreferences(MODE_PRIVATE).edit().putInt("listPosition", currentVisiblePosition).apply();
    

    then restore position like this

     if (getItemCount() == 0) {
         int savedListPosition = getPreferences(MODE_PRIVATE).getInt("listPosition", 0);
         recyclerView.getLayoutManager().scrollToPosition(savedListPosition); }
    

    this last code should be added inside an event of the Adapter (not sure witch event but in my case was onEvent() - com.google.firebase.firestore.EventListener)

提交回复
热议问题