Junior — Middle
How can navigation between fragments be implemented using FragmentManager?
sobes.tech AI
Answer from AI
To navigate between fragments using FragmentManager, the following steps are usually performed:
- Obtain an instance of FragmentManager from the activity or another fragment:
FragmentManager fragmentManager = getSupportFragmentManager();
- Begin a fragment transaction:
FragmentTransaction transaction = fragmentManager.beginTransaction();
- Replace the current fragment with a new one using the
replacemethod or add a new fragment withadd:
transaction.replace(R.id.fragment_container, newFragment);
- Add the transaction to the back stack if you want the user to be able to return back:
transaction.addToBackStack(null);
- Commit the transaction:
transaction.commit();
Example:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, new ExampleFragment());
transaction.addToBackStack(null); // to enable back navigation
transaction.commit();
Thus, navigation is implemented through managing fragment transactions and the back stack in FragmentManager.