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 ?