Junior — Middle
How can you add and display a Fragment in an Activity in Android?
sobes.tech AI
Answer from AI
To add and display a Fragment in an Activity in Android, the FragmentManager and fragment transactions are usually used.
Example of adding a Fragment to an Activity:
// Get the FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// Create an instance of the fragment
MyFragment fragment = new MyFragment();
// Begin a transaction
FragmentTransaction transaction = fragmentManager.beginTransaction();
// Add the fragment to a container with id R.id.fragment_container
transaction.add(R.id.fragment_container, fragment);
// Commit the transaction
transaction.commit();
In the layout of the Activity, there should be a container, such as a FrameLayout with the id fragment_container, where the fragment will be added.
To replace a fragment, the replace method is used instead of add. You can also add the transaction to the back stack to enable returning to the previous state when pressing the back button.