user2278298
user2278298

Reputation: 47

How to change fragments within activity and save state

I have an activity that would have fragments dynamically added using the method below.

FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
FragmentA fragmentA = new FragmentA();
transaction.add(R.id.fragment_container, fragmentA, "fragmentA");
    transaction.addToBackStack("fragmentA");
    transaction.commit();

FragmentA has a TextView. I have a navigation drawer on my activity and want to switch between fragments (for example FragmentA, FragmentB, and FragmentC) depending on which item was clicked in the navigation drawer. How do I save the state of the fragments when changing to another fragment. I've implemented onSavedInstance(Bundle outState) and onActivityCreated(Bundle savedInstanceState) but savedInstanceState is always null. I want to be able to save the fields of FragmentA when changing from FragmentB and then changing back to FragmentA from FragmentB.

I cannot save the state when pressing the backstack. It seems like the fields are not being saved.

What are the correct ways to do this?

Upvotes: 1

Views: 1738

Answers (3)

user2278298
user2278298

Reputation: 47

I found a quick way to maintain the state of each fragment at the below link.

How do I restore a previously displayed Fragment?

I didn't realize that FragmentTransaction had a hide() method to hide the view of the current fragment and a show() method to show it again.

Upvotes: 0

umerk44
umerk44

Reputation: 2817

Fragment's onSaveInstanceState(Bundle outState) will never be called unless fragment's activity call it on itself and attached fragments. Thus this method won't be called until something (typically rotation) force activity to SaveInstanceState and restore it later.

So In on createView you can do something like that . . .

Bundle mySavedInstanceState = getArguments();
 String value = mySavedInstanceState.getString(KEY);

. .

Save value in onPause() method

@Override
    public void onPause() {
        super.onPause();
        String value = //get value from view;

        getArguments().putString(KEY, value);
    } 

Upvotes: 1

Want2bExpert
Want2bExpert

Reputation: 527

You can use SharePrefrences to save Data in FragmentA and read it when it is called again. Additional advantage is that the Data saved in SharePreferences can be read in other fragments if need be.

Useful Links on Fragments;
- https://developer.android.com/training/basics/fragments/index.html

-http://www.vogella.com/tutorials/AndroidFragments/article.html

Upvotes: 0

Related Questions