Creating and Using Android Fragments dynamically

Android fragments are the main component in android development, it’s added fragment component in Android 3.0 (API level 11), primarily to support more dynamic and flexible. Fragments are a 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 Android Fragments dynamically

Creating and Using Fragments in Android :

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

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

2. Add following Strings in app>res>values> strings.xml, Always recommend to use the standard way of development. It will be easy to change in the future.

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

Added new colors bluegrayteal and white.

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

with <TextView> Widget.

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

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

added <FrameLayout> to show fragment dynamically and 2 button for android fragments transaction.

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

Add following code:

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

Add following code:

9. Final add following code in app>java>

Android Fragments dynamically Output Screen shot :


android fragments example

Source code of Android Fragments dynamically example:


Development environment

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

Bonus: Here is the Android Fragment example – Kotlin [static] in the latest technology stack.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.