Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically removing fragments and saving their UI transformations

I have a couple of fragments which substitute one for another. The UI of these fragments changes and I need to hold it's new state. So the code looks pretty trivial:

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager
            .beginTransaction();

    if (mStepTwo == null) {
        mStepTwo = new QuizStepTwo();
        mStepTwo.setListener(mStepTwoListener);
    } else {
        fragmentTransaction.remove(mStepTwo);
    }

    fragmentTransaction.replace(R.id.step_holder, mStepTwo);
    fragmentTransaction.addToBackStack("second_step");

    fragmentTransaction.commit();

However when I replace the second step with the first, for instance by pressing the back-button,- its' UI state rolls back to initial.

How do I hold the state ? OnSaveInstanceState ? or something more comfortable ?

Similar questions: Android Fragment view state within a tab host, How to restore Android fragment view state

like image 417
midnight Avatar asked Dec 29 '12 07:12

midnight


People also ask

What are UI fragments?

A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own--they must be hosted by an activity or another fragment.

What is called when the fragment is detached from the activity?

The onDetach() callback is invoked when the fragment has been removed from a FragmentManager and is detached from its host activity. The fragment is no longer active and can no longer be retrieved using findFragmentById() . onDetach() is always called after any Lifecycle state changes.

What does the onCreateView () method return if a fragment doesn't have any UI?

These files contain only the onCreateView() method to inflate the UI of the fragment and returns the root of the fragment layout. If the fragment does not have any UI, it will return null.

How do you save instance state of fragments in Backstack?

Various Android system operations can affect the state of your fragment. To ensure the user's state is saved, the Android framework automatically saves and restores the fragments and the back stack. Therefore, you need to ensure that any data in your fragment is saved and restored as well.


1 Answers

I haven't used this, so mileage may vary. You could try using the FragmentManager.saveFragmentInstanceState method when replacing Fragments, then use Fragment.setInitialSavedState method when restoring the Fragment. From the docs, it sounds like it may only work if making a new Fragment of the same type, so unsure if this will work with your current implementation.

like image 137
Jason Robinson Avatar answered Oct 01 '22 12:10

Jason Robinson