A fragment is a part of an activity which enables more modular activity design. It represents a particular operation or interface running within a large activity. Fragments are embedded within activities, fragments are not independent entities; they are subservient to a single activity and fragments were added to the android API version 11 (Honeycomb). In this tutorial, you will learn to make and implement fragment in your android application.
This example project of this tutorial will consist of a single activity and three fragments. Each fragments contain an TextView. Two fragments are vertically placed and one is horizontally.
Android Example: How to Create Android Application with Fragments
Let’s start by creating new android project called Android Fragment Example. You need to create three XML layout file and three java file.
Create three XML layout file fragment_layout1.xml, fragment_layout2.xml, fragment_layout3.xml with TextView and with different background color and text in text view. Following is the content of different XML layout file.
Now you need to create three java files Fragment1.java, Fragment2.java, Fragment3.java and extend them to Fragment and override onCreateView then return inflater to the XML layout file. Following is the complete java code of these three file.
Open your main XML layout file and add three fragment with android:name=”com.viralandroid.androidfragmenttutorial.Fragment1″, android:name=”com.viralandroid.androidfragmenttutorial.Fragment2″ and android:name=”com.viralandroid.androidfragmenttutorial.Fragment3″. Following is the complete content of activity_main.xml file.
Your main java activity file will look like this.
Now, run your Android Fragments Tutorial with Example application, you will see the content of different fragment in a single activity. First two fragments are vertical and third fragment is horizontal which will look like above screenshot.