Navonod
Navonod

Reputation: 63

Understanding Dynamic Fragment Loading

In the Android Tutorial, under Building a Flexible UI, the Fragment instantiation given in the example happens in an Activitiy's onCreate() as follows:

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check that the activity is using the layout version with
    // the fragment_container FrameLayout
    if (findViewById(R.id.fragment_container) != null) {

        ...

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();
    }
}

Without including the if (findViewById(R.id.fragment_container) != null) check, my own example fails on startup with:

IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

My question is:

What does the if check do? I don't understand the commented explanation in the tutorial example. My understanding is that for some reason, the onCreate() is being called more than once during the activity lifecycle, but I don't know why? My knowledge of the activity lifecycle is admittedly minimal.

Upvotes: 0

Views: 61

Answers (2)

Antoine Baqain
Antoine Baqain

Reputation: 392

it is simple Navonod,

if (findViewById(R.id.**fragment_container**) != null) {

  getSupportFragmentManager().beginTransaction().add(R.id.**fragment_container**,firstFragment).commit();

}

in res/layout/news_articles.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

So it is already created by the first time the app calls the theme up, this is why we check findViewById(R.id.fragment_container) != null. However, if you dynamically delete it during app runtime, this code will ensure you get it back safely into a FrameLayout that fragments should reside in.

P.S: there isn't actually two calls for onCreate here :)

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006604

What does the if check do?

It checks to see if the container exists. You cannot add a fragment to a container that does not exist.

Upvotes: 2

Related Questions