Junior — Middle
How is a Fragment integrated into an existing Activity?
sobes.tech AI
Answer from AI
To implement a Fragment into an existing Activity in Android, the following steps are usually performed:
- In the
Activitylayout (XML), create a container for the fragment, such as aFrameLayoutwith a unique ID:
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
- In the
Activitycode, create an instance of the desiredFragmentand add it to the container usingFragmentManagerandFragmentTransaction:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
transaction.add(R.id.fragment_container, fragment);
transaction.commit();
- If necessary, you can replace or remove the fragment using the
replace()orremove()methods ofFragmentTransaction.
Thus, the fragment is dynamically embedded into the container within the activity, allowing flexible UI management and component lifecycle control.