Sobes.tech
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:

  1. Obtain an instance of FragmentManager from the activity or another fragment:
FragmentManager fragmentManager = getSupportFragmentManager();
  1. Begin a fragment transaction:
FragmentTransaction transaction = fragmentManager.beginTransaction();
  1. Replace the current fragment with a new one using the replace method or add a new fragment with add:
transaction.replace(R.id.fragment_container, newFragment);
  1. Add the transaction to the back stack if you want the user to be able to return back:
transaction.addToBackStack(null);
  1. 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.