I have only one activity
and multiple fragments
in my application.
Two main fragment A(left) and B(right).
Fragment A1 called from A B1 called from B B2 called from B1
All fragments
have individual back buttons.
So when I press back button of fragment
A1, it should go back to A, similarly when Back button from B2 is pressed, B1 appears and from B1 to B and so on.
How to implement this type of functionality?
2 Answers. Show activity on this post. and when you click on back button in the toolbar programmatically go back to the previous fragment using following code. Show activity on this post.
Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.
public void onBackPressed() { FragmentManager fm = getActivity().getSupportFragmentManager(); fm.popBackStack(); }
I have implemented the similar Scenario just now.
Activity 'A' -> Calls a Fragment 'A1' and clicking on the menu item, it calls the Fragment 'A2' and if the user presses back button from 'A2', this goes back to 'A1' and if the user presses back from 'A1' after that, it finishes the Activity 'A' and goes back.
See the Following Code:
Activity 'A' - OnCreate() Method:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activityA); if (savedInstanceState == null) { Fragment fragInstance; //Calling the Fragment newInstance Static method fragInstance = FragmentA1.newInstance(); getFragmentManager().beginTransaction() .add(R.id.container, fragInstance) .commit(); } }
Fragment : 'A1'
I am replacing the existing fragment with the new Fragment when the menu item click action happens:
@Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_edit_columns) { //Open the Fragment A2 and add this to backstack Fragment fragment = FragmentA2.newInstance(); this.getFragmentManager().beginTransaction() .replace(R.id.container, fragment) .addToBackStack(null) .commit(); return true; } return super.onOptionsItemSelected(item); }
Activity 'A' - onBackPressed() Method:
Since all the fragments have one parent Activity (which is 'A'), the onBackPressed() method lets you to pop fragments if any are there or just return to previous Activity.
@Override public void onBackPressed() { if(getFragmentManager().getBackStackEntryCount() == 0) { super.onBackPressed(); } else { getFragmentManager().popBackStack(); } }
If you are looking for Embedding Fragments inside Fragments, please refer the link: http://developer.android.com/about/versions/android-4.2.html#NestedFragments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With