简体   繁体   中英

How to keep my current fragment on screen rotation

I'm trying to use 3 fragments in one activity and one of that fragment is set as default fragment in onCreate() method and others fragments are calling through some action, so when I rotate the screen the onCreate() method calling again and my current fragment are lost and the default fragment start again but I have to use the default fragment inside the onCreate() method. How can I keep my running fragment on rotate the screen.?

you can use setRetainInstance(true) in your onCreate method.

To retain stateful objects in a fragment during a runtime configuration change:

Extend the Fragment class and declare references to your stateful objects.

Call setRetainInstance(boolean) when the fragment is created.

Add the fragment to your activity.

Use FragmentManager to retrieve the fragment when the activity is restarted.

see documentation of how to handle configuration changes, there is a fragment section

I'm using BottomNavigationView and I encountered the same problem. Solved it by checking if savedInstanceState is null or not before loading the default fragment.

if(savedInstanceState==null) {
   //This is the function you call onCreate to load your Fragments
   loadFragments(new MyDefaultFragment());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM