A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a “sub activity” that you can reuse in different activities).

Google provides the Compatibility Package, a Java library that you can include in an application, implementing support for fragments and other Honeycomb features (loaders).

You can use the Compatibility Package with applications targeting 1.6 (API 4) or later.

For each of the classes in the Compatibility Package, the APIs work almost exactly the same as their counterparts in the latest Android platform. Therefore, you can usually refer to the online documentation for information about the supported APIs.

Today I am going to show you how to add multiple fragments in an one activity.

Define Fragments (activity_main.xml):

Create first Layout (layout_first.xml)

Create Second Layout (layout_second.xml)


Create LayOutOne (LayOutOne.java)

Create LayOutTwo (LayOutTwo.java)

Create MainActivity (MainActivity.java)


Download source code