Introduction to Android Fragments
Fragment is an Android programming aspect that represents a portion of the user interface of what a user sees on the application window. The Android documentation describes Fragment as a portion of user interface in an Activity Object.
In layman’s terms, this means an Activity object can be composed of one or more fragments, each having its own user interface definition.
In this Android fragment tutorial, we will learn how to use fragments in Android with code.
The Basics of Android Fragments
Developers can combine one or more fragments to build a single activity or even reuse fragments across multiple activities.
Fragments were introduced in Android 3.0 to improve the user experience. Classically, developers would have to build a new Activity whenever the user interacted with the application. With Fragments, developers now can update another portion of the UI on the screen that corresponds to the user selection,, without needing to move the user to another screen.
A classic example is a news application that allows a user to select the headline on the left side of the application and it then displays the details of the story on the right side corresponding to user selection.
Fragments can be used in the following scenarios:
- Fragments can be used to build flexible user interfaces across different screen sizes.
- Fragments can be used to provide Fixed/Scrolling/swipe tab displays.
- Fragments can be used where dialog boxes are needed.
- Fragments can be used to build action bar customization with the list and tab modes.
Fragment have the following characteristics
- A fragment is always embedded in an activity. It does not have existence outside of one.
- It has its own lifecycle; however, it is directly impacted by the host activity lifecycle.
- A fragment object processes its own events.
- Fragments can be dynamically added or removed from an Activity, based on user interaction with the application. This can happen when the host Activity is in the “running” state.
- Fragments support transaction with an Activity. In other words, you can click the “Back” button and undo a fragment activity when you perform a fragment transaction.
A fragment lives in the ViewGroup of the host Activity’s view hierarchy.
Creating a Fragment in Android
Creating a fragment is simple and involves four steps:
- Extend Fragment class.
- Provide appearance in XML or Java.
- Override onCreateView to link the appearance.
- Use the Fragment in your activity.
There are three methods, at a minimum, that we need to implement for a fragment.
- onCreate(): This method is called when the fragment is created by Android System. Use this method to initialize necessary components of the fragment that you want to keep when the fragment is paused/stopped and then resumed.
- onCreateView(): This method is called when the user interface for the fragment needs to be drawn for the first time. This method returns a view.
- onPause(): This method is called when the user is leaving the fragment. In this method, tthe app developer needs to commit any pending changes that need to be brought back when the user resumes.
Besides the base Fragment class, the Android platform offers the following three fragment classes:
- DialogFragment: This class displays a floating dialog.
- ListFragment: This class displays a list of items managed by an adapter.
- PreferenceFragrment: This class offers functionality similar to the “Settings” experience.
Let us create a simple application that demonstrates working with Fragment.
Hands On with Android Fragments
Let’s create a simple Android application that demonstrates working with Activities.
Fire up Android Studio and Start a new Android Studio Project.
Figure 1: Starting a new Android Studio project
Provide FragmentDemo as the Application Name and click Next.
Figure 2: Naming the application FragmentDemo
On the next screen, leave the default values and click Next.
Figure 3: Leaving the default values in place
On the “Add an activity to Mobile” page, choose “Blank Activity with Fragment.” This creates an application with a single activity and a Fragment.
Figure 4: Adding a new blank activity
We then are prompted to customize the activity. We will leave the default values unchanged.
Figure 5: Again, leaving the default values in place
Click Finish to creating the project files.
Let’s look at how Android Studio creates the default application. Open up Project Explorer and expand the /java node and /res node.
Figure 6: Expanding the /java and /res nodes
We can see the following:
- There are two Java files: One for the activity and one for the fragment.
- There are two layout files: One for the activity and one for the fragment.
The fragment_main.xml file (layout file for the fragment) contains the following. Update the layout file to include the highlighted text. This text will make our fragment stand out when it’s loaded into the MainActivity.
<RelativeLayout xmlns_android=
"http://schemas.android.com/apk/res/android"
xmlns_tools="http://schemas.android.com/tools"
android_layout_width="match_parent"
android_layout_height="match_parent"
android_paddingLeft="@dimen/activity_horizontal_margin"
android_paddingRight="@dimen/activity_horizontal_margin"
android_paddingTop="@dimen/activity_vertical_margin"
android_paddingBottom="@dimen/activity_vertical_margin"
tools_context=".MainActivityFragment"
android:background="#33FF00">
<TextView android_text="@string/hello_world"
android_layout_width="wrap_content"
android_layout_height="wrap_content"/>
</RelativeLayout>
We can see that it has a very similar content compared to the activity file.
Next, we observe the Activity file, activity_main.xml.
<fragment xmlns_android=
"http://schemas.android.com/apk/res/android"
xmlns_tools="http://schemas.android.com/tools"
android_id="@+id/fragment"
android_name="com.example.vipul.fragmentdemo.MainActivityFragment"
tools:layout="@layout/fragment_main"
android_layout_width="match_parent"
android_layout_height="match_parent" />
You can see from the activity layout file that it refers to the fragment layout.
The Java file for Fragment (MainActivityFragment.java) contains the following template code:
package com.example.vipul.fragmentdemo; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * A placeholder fragment containing a simple view. */ public class MainActivityFragment extends Fragment { public MainActivityFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main, container, false); } }
We can see that the onCreateView method has been implemented as an override and it calls the helper inflater class to create the view.
Let’s make one change in /res/values/strings.xml to update “Hello World!” to “Hello from fragment!” because this text is being used in the fragment.
When we run our application, we will see the following when the application loads:
Figure 7: The application’s output
We can see that the fragment was loaded (the string helps us correlate).
Now, we will create another simple application where we will demo creating a Fragment in a different manner (without using Android Studio support for Fragments).
Create a new project called FragmentDemo2 and this time choose the template for a blank activity.
Figure 8: Creating a second new project
Figure 9: Choosing the “Phone and Tablet” option
Figure 10: Selecting a blank activity
Figure 11: Naming this “MainActivity”
Click Finish to create the project.
Now, on the Project Explorer, add a new class.
Figure 12: Adding a new class from Project Explorer
Figure 13: Naming the new class “MyFragment”
We will see that a new Java file, MyFragment.java, is created with the following content:
package com.example.vipul.fragmentdemo2; import android.app.Fragment; /** * Created by Vipul on 11/21/2015. */ public class MyFragment { }
As you recall from the basics mentioned before, we need to extend the Fragment class to create an Android fragment.
Make the following highlighted change in your MyFragment class.
package com.example.vipul.fragmentdemo2;
import android.app.Fragment;
/**
* Created by Vipul on 11/21/2015.
*/
public class MyFragment extendsFragment {
}
Next, we need to create a layout file for the fragment. Right-click the /res/layout node and select New -> Layout resource file.
Figure 14: Creating a new Layout resource file
Let’s name it my_fragment_layout and click Ok.
The layout is generated. Here are the contents of the layout file.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns_android= "http://schemas.android.com/apk/res/android" android_orientation="vertical" android_layout_width="match_parent" android_layout_height="match_parent"> </LinearLayout>
To help with identifying the fragment clearly, we will add an EditText and have a background color for our fragment.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns_android= "http://schemas.android.com/apk/res/android" android:orientation="vertical" android_layout_width="match_parent" android_layout_height="match_parent" android:background="#FFBB45"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_gravity="center_horizontal" android:text="This is a fragment"/> </LinearLayout>
Next, we need associate the fragment layout with the fragment class file. Open the MyFragmet.java class and implement the onCreateView method:
//myfragment.java public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.my_fragment_layout, container, false); } }
Lastly, we need to imbibe the fragment into the Activity.
We can use Android Studio support in the Design view for the MainActivity layout file to select a fragment from inside the Custom choices.
Figure 15: Selecting a fragment from the Design view
Open the activity_main layout file in design view and, inside the Palete, click Fragment under the “Custom” section. You will be prompted to select a fragment.
Figure 16: You’re prompted to select a fragment
Now, our application is complete. When we run our application, you will see what’s depicted in Figure 17.
Figure 17: The application, running and displaying its text
We now have fragments in action.
Summary
Today, in this Android Fragment tutorial with examples, we learned the basics of fragments, and creating fragments in Android applications. I hope you have found this information useful. You can download the sample code from the link at the end of this article.
About the Author
Vipul Patel is a technology geek based in Seattle. He can be reached at vipul.patel@hotmail.com. You can visit his LinkedIn profile at https://www.linkedin.com/pub/vipul-patel/6/675/508.