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 ?