Chapter 6 Android - Fragments
Chapter 6 Android - Fragments
A Fragment is a piece of an activity which enable more modular activity design. It will not be
wrong if we say, a fragment is a kind of sub-activity.
A fragment has its own layout and its own behaviour with its own life cycle callbacks.
You can add or remove fragments in an activity while the activity is running.
You can combine multiple fragments in a single activity to build a multi-pane UI.
A fragment can be used in multiple activities.
Fragment life cycle is closely related to the life cycle of its host activity which means
when the activity is paused, all the fragments available in the activity will also be
stopped.
A fragment can implement a behaviour that has no user interface component.
Fragments were added to the Android API in Honeycomb version of Android which API
version 11.
You create fragments by extending Fragment class and You can insert a fragment into your
activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.
Prior to fragment introduction, we had a limitation because we can show only a single activity
on the screen at one given point in time. So we were not able to divide device screen and control
different parts separately. But with the introduction of fragment we got more flexibility and
removed the limitation of having a single activity on the screen at a time. Now we can have a
single activity but each activity can comprise of multiple fragments which will have their own
layout, events and complete life cycle.
Following is a typical example of how two UI modules defined by fragments can be combined
into one activity for a tablet design, but separated for a handset design.
The application can embed two fragments in Activity A, when running on a tablet-sized device.
However, on a handset-sized screen, there's not enough room for both fragments, so Activity A
includes only the fragment for the list of articles, and when the user selects an article, it starts
Activity B, which includes the second fragment to read the article.
First of all decide how many fragments you want to use in an activity. For example let's
we want to use two fragments to handle landscape and portrait modes of the device.
Next based on number of fragments, create classes which will extend the Fragment class.
The Fragment class has above mentioned callback functions. You can override any of
the functions based on your requirements.
Corresponding to each fragment, you will need to create layout files in XML file. These
files will have layout for the defined fragments.
Finally modify activity file to define the actual logic of replacing fragments based on
your requirement.
Types of Fragments
Basically fragments are divided as three stages as shown below.
Single frame fragments − Single frame fragments are using for hand hold devices like
mobiles, here we can show only one fragment as a view.
List fragments − fragments having special list view is called as list fragment
Fragments transaction − Using with fragment transaction. we can move one fragment to
another fragment.
Single frame fragment is designed for small screen devices such as hand hold devices(mobiles)
and it should be above android 3.0 version.
Example
This example will explain you how to create your own Fragments. Here we will create two
fragments and one of them will be used when device is in landscape mode and another fragment
will be used in case of portrait mode. So let's follow the following steps to similar to what we
followed while creating Hello World Example −
Ste Description
p
1 You will use Android StudioIDE to create an Android application and name it
as MyFragments under a package com.example.myfragments, with blank Activity.
2 Modify main activity file MainActivity.java as shown below in the code. Here we
will check orientation of the device and accordingly we will switch between
different fragments.
4 Create layouts
files res/layout/lm_fragment.xml and res/layout/pm_fragment.xml and define your
layouts for both the fragments.
7 Run the application to launch Android emulator and verify the result of the changes
done in the application.
package com.example.myfragments;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
@Override
/**
*/
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
/**
*/
fragmentTransaction.replace(android.R.id.content, ls_fragment);
}else{
/**
*/
fragmentTransaction.replace(android.R.id.content, pm_fragment);
fragmentTransaction.commit();
}
}
package com.example.myfragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
*/
@Override
/**
*/
}
Following is the content of PM_Fragement.java file −
package com.example.myfragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
*/
@Override
/**
*/
Create two layout files lm_fragment.xml and pm_fragment.xml under res/layout directory.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#7bae16">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/landscape_message"
android:textColor="#000000"
android:textSize="20px" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#666666">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/portrait_message"
android:textColor="#000000"
android:textSize="20px" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment
android:name="com.example.fragments"
android:id="@+id/lm_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment
android:name="com.example.fragments"
android:id="@+id/pm_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
<resources>
</resources>
Let's try to run our modified MyFragments application we just created. I assume you had
created your AVD while doing environment set-up. To run the app from Android Studio, open
one of your project's activity files and click Run icon from the tool bar. Android Studio installs
the app on your AVD and starts it and if everything is fine with your set-up and application, it
will display Emulator window where you will click on Menu button to see the following
window. Be patience because it may take sometime based on your computer speed −
To change the mode of the emulator screen, let's do the following −
Once you changed the mode, you will be able to see the GUI which you have implemented for
landscape mode as below −
This way you can use same activity but different GUI's through different fragments. You can
use different type of GUI components for different GUI's based on your requirements.
The basic implementation of list fragment is for creating list of items in fragments
LIST IN FRAGMENTS
Example
This example will explain you how to create your own list fragment based on arrayAdapter. So
let's follow the following steps to similar to what we followed while creating Hello World
Example −
Ste Description
p
1 You will use Android Studio to create an Android application and name it
as SimpleListFragment under a
package com.example.tutorialspoint7.myapplication, with blank Activity.
2 Modify the string file, which has placed at res/values/string.xml to add new string
constants
5 Run the application to launch Android emulator and verify the result of the changes
done in the application.
Before start coding i will initialize of the string constants inside string.xml file under res/values
directory
<resources>
<string name="app_name">ListFragmentDemo</string>
<string name="action_settings">Settings</string>
<string name="imgdesc">imgdesc</string>
<string-array name="Planets">
<item>Sun</item>
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
<item>Jupiter</item>
<item>Saturn</item>
<item>Uranus</item>
<item>Neptune</item>
</string-array>
</resources>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/fragment1"
android:name="com.example.tutorialspoint7.myapplication.MyListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="@android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
</LinearLayout>
package com.example.tutorialspoint7.myapplication;
import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
@Override
return view;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
R.array.Planets, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
@Override
package com.example.tutorialspoint7.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
</intent-filter>
</activity>
</application>
</manifest>
Capture the state of each view in both the start and end scenes.
Create an Animator based on the differences that will animate the views from one scene
to the other.
Example
This example will explain you how to create your custom animation with fragment transition .
So let's follow the following steps to similar to what we followed while creating Hello World
Example −
Ste Description
p
1 You will use Android Studio to create an Android application and name it
as fragmentcustomanimations under a
package com.example.fragmentcustomanimations, with blank Activity.
4 Create a folder, which is placed at res/ and name it as animation and add
fragment_slide_right_enter.xml
fragment_slide_left_exit.xml, ,fragment_slide_right_exit.xml and
fragment_slide_left_enter.xml
6 Run the application to launch Android emulator and verify the result of the changes
done in the application.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="@string/hello_world"
android:textAppearance="?android:attr/textAppearanceMedium" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/fragment1"
android:name="com.pavan.listfragmentdemo.MyListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="100dp" android:valueTo="0dp"
android:valueType="floatType"
android:propertyName="translationX"
android:duration="@android:integer/config_mediumAnimTime" />
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="0.0" android:valueTo="1.0"
android:valueType="floatType"
android:propertyName="alpha"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="0dp" android:valueTo="-100dp"
android:valueType="floatType"
android:propertyName="translationX"
android:duration="@android:integer/config_mediumAnimTime" />
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="1.0" android:valueTo="0.0"
android:valueType="floatType"
android:propertyName="alpha"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="-100dp" android:valueTo="0dp"
android:valueType="floatType"
android:propertyName="translationX"
android:duration="@android:integer/config_mediumAnimTime" />
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="0.0" android:valueTo="1.0"
android:valueType="floatType"
android:propertyName="alpha"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="0dp" android:valueTo="100dp"
android:valueType="floatType"
android:propertyName="translationX"
android:duration="@android:integer/config_mediumAnimTime" />
<objectAnimator
android:interpolator="@android:interpolator/decelerate_quint"
android:valueFrom="1.0" android:valueTo="0.0"
android:valueType="floatType"
android:propertyName="alpha"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
/**
*/
int mStackLevel = 1;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_stack);
// Watch for button clicks.
button.setOnClickListener(new OnClickListener() {
addFragmentToStack();
});
if (savedInstanceState == null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
else
mStackLevel = savedInstanceState.getInt("level");
@Override
super.onSaveInstanceState(outState);
outState.putInt("level", mStackLevel);
}
void addFragmentToStack() {
mStackLevel++;
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.animator.fragment_slide_left_enter,
R.animator.fragment_slide_left_exit,
R.animator.fragment_slide_right_enter,
R.animator.fragment_slide_right_exit);
ft.replace(R.id.simple_fragment, newFragment);
ft.addToBackStack(null);
ft.commit();
int mNum;
/**
* as an argument.
*/
static CountingFragment newInstance(int num) {
args.putInt("num", num);
f.setArguments(args);
return f;
/**
*/
@Override
super.onCreate(savedInstanceState);
/**
* instance number.
*/
@Override
View tv = v.findViewById(R.id.text);
tv.setBackgroundDrawable(getResources().
getDrawable(android.R.drawable.gallery_thumb));
return v;
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fragmentcustomanimations"
android:versionCode="1"
android:versionName="1.0" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.fragmentcustomanimations.MainActivity"
android:label="@string/app_name" >
<intent-filter>
</intent-filter>
</activity>
</application>
</manifest>