Question

So I followed this guide on Android Developers. They suggest to use fragments for showing settings to user.

I created the xml and strings and the fragment:

public class SettingsFragmentApp extends PreferenceFragment{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.preferences_app);
    }
}

I want to show this on my MainActivity page without creating another activity that only hosts this fragment (I think the later optioon recommended by google kills the point...why should I create another activity for just a fragment?). So I added an option to the MENU and I handle it like this in the MainActivity:

        //inside onOptionsItemSelected(MenuItem item)
        case (R.id.action_settings_user):
            getFragmentManager().beginTransaction().replace(android.R.id.content,
                    new SettingsFragmentUser()).commit();
            return true;

This way the setting fragments shows up as expected, but as soon as user hits back button the application exits because it was still on MainActivity.

So the question is how can I handle the back button in such a way that it saves the settings changes and brings back user to the MainActivity?

Was it helpful?

Solution

If you want back button functionality you have to add the Fragment to the back stack in the transaction.

FragmentManager manger = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.flFragmentContainer, fragment);
transaction.addToBackStack(null); // Add fragment to back stack.
transaction.commit();

But this is not recommended. The reason they suggest you use an extra Activity is so you can build the navigation stack with Activities instead of fragments. Building a navigation stack with Fragments can become problematic very quickly. Activities are just supposed to be container for Fragments. As such in any app you are going to have many Activities that do not contain anything aside from a Fragment and these Activities are just used to build a navigation stack. In really big apps I tend to write one abstract base Activity that implements all the base features you need and reuse this on Activity as much as possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top