简体   繁体   中英

How can I restore the state of an AdapterViewFlipper in a Fragment?

I have a Fragment that shows different view by a AdapterViewFlipper . The AdapterViewFlipper is being set with MyCustomAdapter that contains 'View 1', 'View 2', 'View 3', and 'View 4', and its in a layout resource file that I inflated in my own Fragment "onCreateView()".

The Problem I'm facing is whenever I rotate my device, the current view in the AdapterViewFlipper goes back to the first view that was added in MyCustomAdapter .

For Example: if the current view in the AdapterViewFlipper is showing 'View 2' and the user rotates the device, it returns back to 'View 1'. So what I'm trying to do is to restore the current view in the AdapterViewFlipper and its state in the Fragment whenever I rotate my device. Although I found this method that says I should declare the android:configChanges attribute at the element in the AndroidManifest and it worked like a charm but when I was reading about it Android didn't recommend it. But this works fine in Activity. So is there a way I can go through this myself?

So the first thing you need to do, is to make sure you are retaining the fragment itself. And not place a new instance every time your activity is re-created.

You can establish that with a simple check in your onCreate() method. You can either check if the savedInstance Bundle parameter to onCreate() is null , in that case only you need to replace your fragment OR check if your fragment is already added to your FragmentManager .

if (savedInstanceState == null) {
    // This is a brand new activity, and not a re-creation due to config change
    getSupportFragmentManager().beginTransaction().replace(id, yourFragmentInstnace, stringTag);
}

OR

if (getSupportFragmentManager().findFragmentByTag(fragmentTag) == null) {
    // This is a brand new activity, and not a re-creation due to config change
    getSupportFragmentManager().beginTransaction().replace(id, yourFragmentInstnace, fragmentTag);
}

And you also need to call setRetainInstance(true) in your fragment's onCreate() or something.

That will retain the same instance of your fragment during a configuration change.

This should automatically allow your AdapterViewFlipper to maintain its UI state, which is the current item it's showing.

You can find a nice example here

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