Junior — Middle
What methods can be used to manage fragments with FragmentManager?
sobes.tech AI
Answer from AI
With FragmentManager, you can manage fragments in the following ways:
- Adding a fragment:
beginTransaction().add(containerId, fragment).commit() - Replacing a fragment:
beginTransaction().replace(containerId, fragment).commit() - Removing a fragment:
beginTransaction().remove(fragment).commit() - Adding a transaction to the back stack for return capability:
addToBackStack(null) - Finding a fragment by tag or id:
findFragmentById()orfindFragmentByTag()
Example of adding a fragment:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.fragment_container, new MyFragment());
transaction.addToBackStack(null);
transaction.commit();