Fragment Manager to Find Fragments in Android

To find Fragments within your Activity, use the Fragment Manager’s findFragmentById method. If you have added your Fragment to the Activity layout in XML, you can use the Fragment’s resource identifier:

MyFragment myFragment =
 (MyFragment)fragmentManager.findFragmentById(R.id.MyFragment);

If you’ve added a Fragment using a Fragment Transaction, you should specify the resource identifier of the container View to which you added the Fragment you want to fi nd. Alternatively, you can use the findFragmentByTag method to search for the Fragment using the tag you specified in the Fragment Transaction:

MyFragment myFragment =
 (MyFragment)fragmentManager.findFragmentByTag(MY_FRAGMENT_TAG);

Populating Dynamic Activity Layouts with Fragments

If you’re dynamically changing the composition and layout of your Fragments at run time, it’s good practice to define only the parent containers within your XML layout and populate it exclusively using Fragment Transactions at run time to ensure consistency when configuration changes (such as screen rotations) cause the UI to be re-created

Populating Fragment layouts using container views

public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 // Inflate the layout containing the Fragment containers
 setContentView(R.layout.fragment_container_layout);
 
 FragmentManager fm = getFragmentManager();
 // Check to see if the Fragment back stack has been populated
 // If not, create and populate the layout.
 DetailsFragment detailsFragment = 
 (DetailsFragment)fm.findFragmentById(R.id.details_container);
 
 if (detailsFragment == null) {
 FragmentTransaction ft = fm.beginTransaction(); 
 ft.add(R.id.details_container, new DetailsFragment());
 ft.add(R.id.ui_container, new MyListFragment());
 ft.commit();
 }
}

Hiding Fragments in layout variations

<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
 android:orientation=”horizontal”
 android:layout_width=”match_parent”
 android:layout_height=”match_parent”>
 <FrameLayout
 android:id=”@+id/ui_container”
 android:layout_width=”match_parent” 
 android:layout_height=”match_parent” 
 android:layout_weight=”1”
 />
 <FrameLayout
 android:id=”@+id/details_container”
 android:layout_width=”match_parent” 
 android:layout_height=”match_parent” 
 android:layout_weight=”3”
 android:visibility=”gone”
 />
</LinearLayout> 

Leave a Comment