What is Fragments in Android :

Android added fragment component in Android 3.0 (API level 11), primarily to support more dynamic and flexible. Fragments are usable portion of user interface in activity. In Activity we can use multiple fragments. Fragments have its own life cycle, but its directly affected by the Activity life cycle. One Fragments can use in Multiple Activities.

Creating and Using Fragments in Android :

In This example we are using 2 Fragments in Activity and changing it on Click button.

1. Create new Android project (How to create android project in Android studio).

2. Add following Strings in app>res>values>strings.xml

3. Add following Strings in app>res>values>colors.xml

4.  Create new fragment layout app>res>layout>”fragment_own.xml”

5.  Create new fragment layout app>res>layout>”fragment_two.xml”

6. Add following line in app>res>layout>activity_main.xml

7.  Create new Fragment class app>src>java>”FragmentOne.java”

Add following code:

8.  Create new Fragment class app>src>java>”FragmentTwo.java”

Add following code:

9. Final add following code in app>java>MainActivity.java

Output Screen shot :

android fragments example

Source code Link GitHub:


Development environment

Android Studio : 2.1.3
compileSdkVersion 24
buildToolsVersion “24.0.1”
minSdkVersion 15 (Ice Cream Sandwich)
targetSdkVersion 24 (Nougat)

Leave a Reply