0

I have simple Fragment and I use RecylerView to list my elements. I want to keep scroll position when I change screen rotation.

Regarding the answer here I added these lines to my Fragment code;

@Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("position", recyclerView.getVerticalScrollbarPosition());
    }

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null) {
            recyclerView.scrollToPosition(savedInstanceState.getInt("position"));
        }
    }

But I have a special case here. Because I have to refresh my adapter when I rotate my screen. I use these lines to refresh:

@Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        refreshAdapter();
    }

    private void refreshAdapter() {
        if (adapter != null) {
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
            adapter.notifyDataSetChanged();
        }
    }

When I comment out refreshAdapter(); line, I can keep my scroll position. But I have to use refreshAdapter(); line.

How can I keep my scroll position with these methods ?

Wicaledon
  • 710
  • 1
  • 11
  • 26
  • Your question has already been asked before. https://stackoverflow.com/questions/27816217/how-to-save-recyclerviews-scroll-position-using-recyclerview-state – Arda Kazancı Aug 16 '22 at 08:18
  • @ArdaKazancı as I said on beginning, I found an answer and I implemented to my code.. but I have additionally special case, I haven't find any similar answer to mine in your link. – Wicaledon Aug 16 '22 at 08:24
  • use diffutiling – Arda Kazancı Aug 16 '22 at 08:25
  • @Wicaledon does save last scroll position then scroll to that pos when sreen rotated is aceptable solution? – KiluSs Aug 16 '22 at 08:40
  • @KiluSs yes please, can you add your code ? I can try my chance – Wicaledon Aug 16 '22 at 08:52
  • @Wicaledon that solution will not keep exactly old recyclerView position. Example, if last visible position is at 1/2 of item 8th, use that solution it will jump to full 8th item after screen is rotated. – KiluSs Aug 16 '22 at 09:06
  • @KiluSs no problem, can you provide the code please – Wicaledon Aug 24 '22 at 07:08
  • @Wicaledon i found this answer https://stackoverflow.com/a/65645518/12070549. May that help – KiluSs Aug 24 '22 at 07:49

0 Answers0