1

I have a RecyclerView in FragmentA. When I open FragmentB and come back to FragmentA, RecyclerView return to top. But I want to remain at same positon. I resarched in SO and I used onSaveInstanceState() method but it doesn't work. Later I saw this answer and it worked: https://stackoverflow.com/a/57766617/10795859

The solution is: Take the View reference variable and set view in OnCreateView. Check if view already exists in this variable, then return same view.

 private View fragmentView;

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    if (fragmentView != null) {
        return fragmentView;
    }
    View view = inflater.inflate(R.layout.yourfragment, container, false);
    fragmentView = view;
    return view;
}

But I'm not sure it is a reliable solution. So is this correct way or Should I use another way ?

Mehmet Gür
  • 503
  • 7
  • 20
  • Hi! How did you used onSaveInstanceState? did you use savedInstanceState then? and did you debug to see where's the problem? Becouse I honestly think, that saving state is the right way! – barkatme Apr 07 '20 at 20:02
  • The main problem is, that you need to handle it in the parent `Activity` and not inside the `Fragment`. eg; adding `Fragment ` in `Activity` `onCreate()` ...when `savedInstanceState == null`... saving the state manually is not required, this is done by the `FragmentManager`; one just should not destroy the instance. – Martin Zeitler Apr 07 '20 at 20:14
  • Fragments already save and restore their view state correctly. RecyclerView restores its scroll position when you call `setAdapter`, but your code here doesn't tell us when you're calling `setAdapter` - if it is when your adapter is still empty, then your scroll position is being thrown out. – ianhanniballake Apr 08 '20 at 00:12

0 Answers0