Android Fragment :

A Fragment represents a behavior or a portion of user interface in an Activity. Fragments mus be embedded with activities, they can not run independent.Single Activity can use multiple fragments and fragment usable in several activities.Each fragment has its own lifecycle, closely associated with the lifecycle of its host activity. a fragment may be a static a part of an activity or instantiated automatically during the activity’s creation or you can create(), add(), and remove() fragments dynamically in an activity at run-time.

Android Fragment tutorial example

Solution Steps Android Fragment : Implemented in Honeycomb (3.0) or Later

The primary classes related to fragments are:
The base class for all fragment definitions
The class for interacting with fragment objects inside an activity
The class for performing an atomic set of fragment operations

1. Create Android New project (Click here for setup new Android project).

2. Add Following xml code into activity_main.xml

File : res/layout/activity_main.xml

In this example we are using two Buttons One for FragmentOne or second for FragmentTwo and one Fragment Layout for show fragments.

3. Create “fragment_one.xml” file and add following code.

File : res/layout/fragment_one.xml

4. Create “fragment_two.xml” file and add following code.

File : res/layout/fragment_tow.xml

5. Open “” file and add following JAVA code.

File : src/package-name/

Initialize fragment_one layout:

5. Open “” file and add following JAVA code.

File : src/package-name/

Initialize fragment_two layout:

6. Open “” file and add following JAVA code.

File : src/package-name/

In tutorial by default FragmentOne displayed , after click Button One or Two fragment it will display respective fragment layout.


Output of  Android Fragment Example :

Android fragment tutorila example

Note : This example (Project) is developed in Eclipse Version Kepler,tested on Android 4.4.4 (KitKat Version) and 5.0 (lollipop) and SDK build-tools 24.1



Download Android Fragment example  Source code :

  1. Please, can you tell me how to make the fragment cover the main activity? I’ve tried using frame layout to put the fragment container in the front, but it’s see through, I even can still click the button behind it. Please tell me how to do it properly. Thanks.

  2. FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();\
    I have got error many. How above line error can remove. Please reply.\

Leave a Reply