简体   繁体   中英

Restoring state of fragment

I have a Fragment F attached on Activity A. When another activity becomes front-activity it is called onSaveInstanceState . I've overrided that function and it looks like:

public void onSaveInstanceState(Bundle outState){
 saveState_to_outstate
}

Now, when the Fragment F is front again it is called onViewCreated(View view, Bundle savedInstanceState) . I would like to restore previously saved state but I cannot because savedInstanceState is null though it was written before in onSaveInstanceState .

Why it happened?

If you want to restore Fragment F with previous Data. As according to my knowledge you should perform inside onViewStateRestored() method of Fragment.

OnViewStateRestored (Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored. you Should visit this link for your reference: Fragment

Method A: You can pass the data from Activity A to Fragment F by bundle or intent. it's similar to usage of saving instance. Send data from activity to fragment in android

MethodB: You can only use following function with onCreate() at the same place, either fragment F or Activity A.

public void onSaveInstanceState(Bundle outState){ outState.putInt("STATE_NAME", 123);//123 is the data you gonna save super.onSaveInstanceState(outState);//Don't forget to put this }

MethodC: Use hardcode-like SharePreference Android Shared preferences example ,it's also like the bundle and intent, and it won't be effected by Activity or fragment life periods.

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