3

I manage two fragments in my MainActivity.

One of them is a subclass of ListFragment to show a list of items.

The main idea is to navigate to another list view when user tap one of the items, and the user can go back to the previous list view when tapping back button.

The code for transmit to a new list is shown as follow:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
NewFragment newFragment = new NewFragment();
newFragment.setArguments(getIntent().getExtras());
transaction.replace(R.id.fragment_layout, newFragment);
transaction.addToBackStack(null);
transaction.commit();

However, I just simply exit the application other than going back to the previous view. What am I doing wrong?

Dragon warrior
  • 1,644
  • 2
  • 24
  • 37
  • i noticed something simmilar, it was working fine but then i switched from the supportfragmentmanager to the normal one i guess android 4's non support version is maybe broken...?? – boscowitch Feb 08 '15 at 19:56
  • oh I think in my case its a bad case of mixing support library with normal ones.. since i had to switch from the support fragment manager to support PreferenceFragment... guess I will have to switch back... and do some hacky workaround... – boscowitch Feb 08 '15 at 20:17

2 Answers2

0

unlike activities, with fragments you have to explicitly add things onto the "back stack". basically, when your app displays a new fragment such that'd you like back to return to the preview fragment, you call FragmentTrasaction.addToBackStack().

the framework handles popping the fragment off the back stack when the user presses back. if you need something more complex, you can override the back button press for your fragment. this question covers that,

Android Fragment handle back button press

Community
  • 1
  • 1
Jeffrey Blattman
  • 22,176
  • 9
  • 79
  • 134
-2

The back button closes the top Activity and does not navigate back in your Fragment history. You have to do that yourself with popBackStack()

SimonSays
  • 10,867
  • 7
  • 44
  • 59