In this tutorial, we will learn about Fragments of Android and make an example application. Until now, we have used Activities for each different screen.
Assume an application requests authentication from user. The user who forget the password uses the ‘Forgot Password Screen’ right ? If we observe this situation on the basis of activities :
The user opens the application and Wellcome Page Activity starts. Then clicks the login button and Login Page Activity place over Wellcome Page. Finally clicks ‘forgot password’ button and user reaches the Forgot Password Activity. So each activity places over previous one and it is holden in stack.
But what if we keep activity as single and change pages in the activity ? This brings us to Fragment concepts. So in this scenario you can consider activitiy as a single frame and fragments place or remove from that frame according to the user interaction.
It is just that simple. Lets continue with demo application.
- Open a new Android Studio project.
- First of all, we need to design our activity layout. Open your
res/layout/activity_main.xml
and copy below. (I assume that your MainActivity.java and activity_main.xml files are generated automatically)
12345<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/frame"/> - FrameLayout is container of fragments. As you see at figures at the beginning of the tutorial, Activity has just a frame. This FrameLayout is the frame we talk about.
- Our container is ok. Next is creating a fragment and configuring its layout. But before, I need to give some information about fragments in android.
Fragments
Lets read the definition of fragments given by developer.android.com
A Fragment represents a behavior or a portion of user interface in an Activity . You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a “sub activity” that you can reuse in different activities). |
Like above, fragment is considered as a ‘sub activity’ and it has own lifecycle. Below figure is taken from developer.android.com and you can learn more from here.
As a result, you can consider fragments as sub activities running in actual activities.
- Right now we need to create a fragment but before lets create a layout file for this fragment. Right click on your
res/layout
folder and create a new layout resource file. Name it as ‘fragment_my’
- Open your
res/layout/fragment_my.xml
and put a textview in it like below.
12345678910111213141516<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:id="@+id/textview"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginRight="20dp"android:layout_marginLeft="20dp"android:textSize="20sp"android:textColor="#000000"android:layout_centerInParent="true"/></RelativeLayout>
- Fragment layout is ok. Lets create the fragment. Right click on your package and create a new java class.Name it as ‘MyFragment’
- Turn your class into a Fragment like below. In
onCreateView
method you can return your inflated layout. In other words, you can set your fragment’s layout inonCreateView
phase.
12345678910111213141516import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;public class MyFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {/*Return inflated layout which is intended to be in this fragment*/return inflater.inflate(R.layout.fragment_my,container,false);}}
- Fragment layout has a textview. Lets reach that textview and manipulate it. I prefer do these reaching view elements in fragment layout works in
onViewCreated
phase of lifecycle. You can understand why from its name : onViewcreatED. All layout is applied when this phase came. So we can safely access view elements here.
12345678910111213141516171819202122232425import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;public class MyFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {/*Return inflated layout which is intended to be in this fragment*/return inflater.inflate(R.layout.fragment_my,container,false);}@Overridepublic void onViewCreated(View view, Bundle savedInstanceState) {super.onViewCreated(view, savedInstanceState);/* Layout has been applied to the fragment at this point so we can safelyaccess the elements in this layout. getView() method returns what we inflate in onCreateView.*/TextView textView = (TextView)getView().findViewById(R.id.textview);textView.setText("Here is MyFragment. You can play with fragment_my.xml and change appearance in your way.");}}
- We are ok with the fragment and its layout. Lets place it in activity frame. Open your
MainActivity.java
and add below signed part.
123456789101112131415161718import android.app.Activity;import android.app.FragmentTransaction;import android.os.Bundle;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);/*Create a fragment and place it in frame*/MyFragment myFragment = new MyFragment();FragmentTransaction transaction = getFragmentManager().beginTransaction();transaction.replace(R.id.frame,myFragment);transaction.commit();}}
- All fragment transactions (adding-removing-replacing with another one) are managed by
FragmentManager
object and you can get it callinggetFragmentManager()
method in Activity. - Ok thats all. You can run your application.
![]() If you don’t know how to open an existing Android Studio Project, follow this tutorial. |