Android: How to create a new Fragment and put it in a layout

I’ve been working on an Android app that uses a navigation drawer, and uses fragments for each item in the drawer that you tap on. One of the items in the nav drawer is a “Preferences” item, so when I tap on that item, I run the following code from my nav drawer code:

Fragment prefsFragment = new PreferencesFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, prefsFragment).commit();

What this does is create a new instance of my PreferencesFragment, and then puts that fragment into what I call the content_frame. This content_frame refers to a FrameLayout that I’ve defined in my activity_main.xml layout file. This fragment basically replaces whatever else was in that FrameLayout before this call. I believe this is the correct approach, at least with the navigation drawer code that I’m using.

My main layout file

For the record, my activity_main.xml file currently looks like this:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#d0111111"/>

</android.support.v4.widget.DrawerLayout>

I made the FrameLayout tag bold in that file; that’s where all of my fragments are placed when I run the code I showed above.

When is a Fragment destroyed?

This code just made me wonder, “When is this fragment destroyed?” To test this I added an onDestroy() method to my fragment and logged a message when it was destroyed. onDestroy is actually called as soon as I switch to another fragment via my Navigation Drawer interface. That’s good to know.

Here’s a link to the official Android Fragments documentation page. Here’s another link to a useful article that discusses the fragment lifecycle, and shares some source code via Github to demonstrate it all.