Search code examples
androidandroid-activityfragmentback

Getting back to a fragment keeping its previous state


I am an old Android programmer, but I used to use only Activities and I'm quite new with Fragments.

I've created an application with a menu bar (4 buttons) that, when clicked, are supposed to load each one a different Fragment above the menu bar. The problem is that each time I click on one of the menu bar buttons, it reloads entirely the fragment and I would like it to show the Fragment on its previous state (just like the device Back button does).

How can I do such a thing?

Call from the main activity:

    Fragment my_fragment = new MyFragment();
    FragmentManager fragment_manager = getSupportFragmentManager();
    FragmentTransaction fragment_transaction = fragment_manager.beginTransaction();
    fragment_transaction.replace(R.id.fragment_container, my_fragment);
    fragment_transaction.addToBackStack(null);
    fragment_transaction.commit();

and most my MyFragment process code is in the function

onActivityCreated


Solution

  • You also can use onSaveInstanceState method as in activities,to restore data use Bundle savedInstanceState object, for example

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("test", 1);
    }
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            int testValue = savedInstanceState.getInt("test", 0);
        }
    }
    

    http://developer.android.com/guide/components/fragments.html