Scroll State Of Recyclerview Inside ViewPager Tab Fragment Not Saved When Device Orientation Is Handled Manually Using OnConfigurationChanged()
What I want to achieve: FragmentOne is under Tab1 and FragmentTwoPortrait is under Tab2. I want to save the state of the recyclerview of FragmentTwoPortrait, then restore the frag
Solution 1:
First of all get current visible position of your RecyclerView
by adding addOnScrollListener()
as follows :
private int position=0;
myRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE){
position = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
}
}
});
Now save the current visible position in onSaveInstanceState()
method as follows :
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("visiblePosition", position);
}
Then in Your onActivityCreated()
get current visible position from savedInstanceState
and set scroll position as follows:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState.getInt("visiblePosition")>0)
myFriendsRecyclerView.scrollToPosition(savedInstanceState.getInt("visiblePosition"));
}
I hope its work for you thank you
Solution 2:
If you want same behaviour in both portrait and landscape mode then try not to save any configuration
In AndroidManifest for this particular activity
android:configChanges="keyboardHidden|orientation"
Post a Comment for "Scroll State Of Recyclerview Inside ViewPager Tab Fragment Not Saved When Device Orientation Is Handled Manually Using OnConfigurationChanged()"