serenskye
serenskye

Reputation: 3467

Android Fragments - dealing with the backbutton

I am launching some fragments from my options menu, for example a preference fragment and a dialog fragment.

When I open the preferences fragment and hit the back button the entire activity closes. This is not the case for the dialog fragment that works as I'd expect.

Could someone explain why this is happening and what is the accepted way of handling please? :)

To launch preference fragment:

getFragmentManager().beginTransaction()
                .add(android.R.id.content, new SettingsFragment())
                .addToBackStack("settings")
                .commit();

Upvotes: 2

Views: 3000

Answers (2)

kdenney
kdenney

Reputation: 18533

Related to my answer here.

I had the exact same problem with the preferences fragment. It seems most people must give up and use a Preference Activity instead.

Your first problem that you are going to encounter is that you need to use replace instead of add when launching the fragment. That code should change to look like so:

getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .addToBackStack("settings")
                .commit();

As for handling the back button, it appears that the "back stack" is something that is not automatically triggered with the system back button. My solution was to manually pop the back stack from the onBackPressed override:

@Override
public void onBackPressed()
{
    if (inSettings)
    {
        backFromSettingsFragment();
        return;
    }
    super.onBackPressed();
}

Whenever I navigate to my preferences fragment, I set the inSettings boolean to true in the activity to retain that state. Here is what my backFromSettingsFragment method looks like:

private void backFromSettingsFragment()
{
    inSettings = false;
    getFragmentManager().popBackStack();
}

Upvotes: 8

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

If there is not any clear reason you named your back stack state, use null as argument:

getFragmentManager().beginTransaction()
                .add(android.R.id.content, new SettingsFragment())
                .addToBackStack(null)
                .commit();

Upvotes: -1

Related Questions