简体   繁体   中英

What mechanism causes a View.onSaveInstanceState to be called in Fragment to Fragment navigation?

There is a lot of noise surrounding this subject on SO and Google, so bear with me.

When performing Fragment to Fragment navigation, you see this lifecycle:

Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView

Fragment2: onCreateView
Fragment2: onStart
Fragment2: onResume

(You can see this in this picture stolen from here ) 在此处输入图像描述

There is no call to a Fragment.onSaveInstanceState as the Fragment instance is still alive - only it's view has been destroyed.

What mechanism therefore is saving the View's state and restoring it, and how?

onSaveInstanceState will be called according to documentation:

This method will occur after onStop() for applications targeting platforms starting with Build.VERSION_CODES.P. For applications targeting earlier platform versions this method will occur before onStop() and there are no guarantees about whether it will occur before or after onPause().

In onSaveInstanceState you can put all the data you want to persist in the bundle

override fun onSaveInstanceState(outState: Bundle) {
// put data you want to persist to outState
super.onSaveInstanceState(outState)

}

And then in onCreate you can check if you need to restore your persisted data:

  override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
  // activity created for the first time
} else {
  // activity re-created, restore data from savedInstanceState
}

}

You can also read more about it here: https://developer.android.com/topic/libraries/architecture/saving-states

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