0

I have an activity that opens PreferenceScreen. When I click 'back' - I expect that the preference screen will be closed and I'll go back to the activity, but instead - the current activity is closed and I go back to the previous activity. How can I fix that?

public class MyActivity extends Activity {
    //....
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return (new Helper()).onOptionsItemSelected_menu(item,this,mFragmentManager);
    }
}


public class Helper {
   // ....

    public boolean onOptionsItemSelected_menu(MenuItem item, Activity activity, FragmentManager mFragmentManager)
    {
        switch (item.getItemId()) {
           case R.id.action_settings:
               MenuHelper.settings(activity, mFragmentManager);
               return true;
           default:
               return onOptionsItemSelected_menu(item, activity, mFragmentManager);
            }
     }

     public static void settings(Activity activity, FragmentManager mFragmentManager) {        
        FragmentTransaction mFragmentTransaction = mFragmentManager
                                .beginTransaction();
        PrefsFragment mPrefsFragment = new PrefsFragment(activity);
        mFragmentTransaction.replace(android.R.id.content, mPrefsFragment);
        mFragmentTransaction.commit();
     }

     public static class PrefsFragment extends PreferenceFragment {
        Activity m_activity;
        public PrefsFragment(Activity activity)
        {
            m_activity = activity;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
     }
}
TamarG
  • 3,522
  • 12
  • 44
  • 74

2 Answers2

1

Daniel's answer is totally correct, though you can achieve same thing just by adding mFragmentTransaction.addToBackStack(null) right before transaction commit.

GnoX
  • 66
  • 3
0

It looks like your issue is that you're replacing the fragment in the current activity with your Preferences screen.

You will have to re-factor your code a bit, but the key is to open a new Activity for your Preferences screen instead of replacing the fragment in the current Activity. This will add a new Activity to the Back Stack for the Preferences screen, and when you click back, it will pop the Preferences Activity from the Back Stack and return you to the previous Activity as you desire.

Edit: Don't re-factor your code, just do what @GnoX suggests.

For more info, see this guide: http://developer.android.com/guide/components/tasks-and-back-stack.html

Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137