UNIT II Android UI Design
UNIT II Android UI Design
Basic UI Designing (Form widgets ,Text Fields , Layouts ,[dip, dp, sip, sp] versus
px)
Intent(in detail)
All components (e.g Button , Slider, Image view, Toast) Event Handling
Adapters and Widgets
Menu
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. There can be more than one fragment in
an activity. Fragments represent multiple screen inside one activity. Android fragment lifecycle
is affected by activity lifecycle because fragments are included in activity. Each fragment has
its own life cycle methods that is affected by activity life cycle because fragments are
embedded in activity.
Following are important points about fragment −
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-plane 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.
Fragment Life Cycle
Android fragments have their own life cycle very similar to an android activity. This section
briefs different stages of its life cycle.
FRAGMENT LIFECYCLE
Here is the list of methods which you can to override in your fragment class −
onAttach()The fragment instance is associated with an activity instance.The fragment and
the activity is not fully initialized. Typically you get in this method a reference to the activity
which uses the fragment for further initialization work.
onCreate() The system calls this method when creating the fragment. You should initialize
essential components of the fragment that you want to retain when the fragment is paused or
stopped, then resumed.
onCreateView() The system calls this callback when it's time for the fragment to draw its
user interface for the first time. To draw a UI for your fragment, you must return a View
component from this method that is the root of your fragment's layout. You can return null if
the fragment does not provide a UI.
onActivityCreated()The onActivityCreated() is called after the onCreateView() method when
the host activity is created. Activity and fragment instance have been created as well as the
view hierarchy of the activity. At this point, view can be accessed with the findViewById()
method. example. In this method you can instantiate objects which require a Context object
onStart()The onStart() method is called once the fragment gets visible.
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.
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are
few common attributes among all the layouts and their are other attributes which are specific
to that layout. Following are common attributes and will be applied to all the layouts:
Attribute Description
android:id This is the ID which uniquely identifies the view.
android:layout_width This is the width of the layout.
android:layout_height This is the height of the layout
android:layout_marginTop This is the extra space on the top side of the layout.
android:layout_marginBottom This is the extra space on the bottom side of the layout.
android:layout_marginLeft This is the extra space on the left side of the layout.
android:layout_marginRight This is the extra space on the right side of the layout.
android:layout_gravity This specifies how child Views are positioned.
android:layout_weight This specifies how much of the extra space in the layout
should be allocated to the View.
android:layout_x This specifies the x-coordinate of the layout.
android:layout_y This specifies the y-coordinate of the layout.
android:layout_width This is the width of the layout.
android:layout_width This is the width of the layout.
android:paddingLeft This is the left padding filled for the layout.
android:paddingRight This is the right padding filled for the layout.
android:paddingTop This is the top padding filled for the layout.
android:paddingBottom This is the bottom padding filled for the layout.
Here width and height are the dimension of the layout/view which can be specified in terms of
dp (Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an
inch), px( Pixels), mm ( Millimeters) and finally in (inches).
You can specify width and height with exact measurements but more often, you will use one
of these constants to set the width or height −
android:layout_width=wrap_content tells your view to size itself to the dimensions
required by its content.
android:layout_width=fill_parent tells your view to become as big as its parent view.
Gravity attribute plays important role in positioning the view object and it can take one or
more (separated by '|') of the following constant values.
View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within
the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/my_button"
Following is a brief description of @ and + signs −
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse
and expand the rest of the ID string and identify it as an ID resource.
The plus-symbol (+) means that this is a new resource name that must be created and added
to our resources. To create an instance of the view object and capture it from the layout, use
the following −
Button myButton = (Button) findViewById(R.id.my_button);
Input controls are the interactive components in your app's user interface. Android provides a
wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check
box, zoom buttons, toggle buttons, and many more.
Example
This example will take you through simple steps to show how to create your own Android
application using Linear Layout. Follow the following steps to modify the Android application
we created in Hello World Example chapter −
Step
Description
1
You will use Android Studio to create an Android application and name it as Demo under a
package com.example.demo as explained in the Hello World Example chapter.
2
Modify the default content of res/layout/activity_main.xml file to include few buttons in linear
layout.
3
No need to change string Constants.Android studio takes care of default strings
4
Run the application to launch Android emulator and verify the result of the changes done in
the application.
Following is the content of the modified main activity file
src/com.example.demo/MainActivity.java. This file can include each of the fundamental
lifecycle methods.
package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/btnStartService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="start_service"/>
<Button android:id="@+id/btnPauseService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="pause_service"/>
<Button android:id="@+id/btnStopService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="stop_service"/>
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>
Now let's change the orientation of Layout as android:orientation="horizontal" and try to run
the same application, it will give following screen –
Android Relative Layout :
Android RelativeLayout enables you to specify how child views are positioned relative to each
other. The position of each view can be specified as relative to sibling elements or relative to
the parent.
Relative Layout
RelativeLayout Attributes
Following are the important attributes specific to RelativeLayout –
Using RelativeLayout, you can align two elements by right border, or make one below another,
centered in the screen, centered left, and so on. By default, all child views are drawn at the
top-left of the layout, so you must define the position of each view using the various layout
properties available from RelativeLayout.LayoutParams and few of the important attributes
are given below –
Sr.N Attribute & Description
o.
1 android:layout_above
Positions the bottom edge of this view above the given anchor view ID and
must be a reference to another resource, in the form "@[+]
[package:]type:name"
2 android:layout_alignBottom
Makes the bottom edge of this view match the bottom edge of the given
anchor view ID and must be a reference to another resource, in the form
"@[+][package:]type:name".
3 android:layout_alignLeft
Makes the left edge of this view match the left edge of the given anchor
view ID and must be a reference to another resource, in the form "@[+]
[package:]type:name".
4 android:layout_alignParentBottom
If true, makes the bottom edge of this view match the bottom edge of the
parent. Must be a boolean value, either "true" or "false".
5 android:layout_alignParentEnd
If true, makes the end edge of this view match the end edge of the parent.
Must be a boolean value, either "true" or "false".
6 android:layout_alignParentLeft
If true, makes the left edge of this view match the left edge of the parent.
Must be a boolean value, either "true" or "false".
7 android:layout_alignParentRight
If true, makes the right edge of this view match the right edge of the
parent. Must be a boolean value, either "true" or "false".
8 android:layout_alignParentStart
If true, makes the start edge of this view match the start edge of the
parent. Must be a boolean value, either "true" or "false".
9 android:layout_alignParentTop
If true, makes the top edge of this view match the top edge of the parent. Must be a boolean
value, either "true" or "false".
10 android:layout_alignRight
Makes the right edge of this view match the right edge of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".
11 android:layout_alignStart
Makes the start edge of this view match the start edge of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".
12 android:layout_alignTop
Makes the top edge of this view match the top edge of the given anchor view ID and
must be a reference to another resource, in the form "@[+][package:]type:name".
13 android:layout_below
Positions the top edge of this view below the given anchor view ID and must be a
reference to another resource, in the form "@[+][package:]type:name".
14 android:layout_centerHorizontal
If true, centers this child horizontally within its parent. Must be a boolean value, either
"true" or "false".
15 android:layout_centerInParent
If true, centers this child horizontally and vertically within its parent. Must be a boolean
value, either "true" or "false".
16 android:layout_centerVertical
If true, centers this child vertically within its parent. Must be a boolean value, either
"true" or "false".
17 android:layout_toEndOf
Positions the start edge of this view to the end of the given anchor view ID and must be
a reference to another resource, in the form "@[+][package:]type:name".
18 android:layout_toLeftOf
Positions the right edge of this view to the left of the given anchor view ID and must be
a reference to another resource, in the form "@[+][package:]type:name".
19 android:layout_toRightOf
Positions the left edge of this view to the right of the given anchor view ID and must be
a reference to another resource, in the form "@[+][package:]type:name".
20 android:layout_toStartOf
Positions the end edge of this view to the start of the given anchor view ID and must be
a reference to another resource, in the form "@[+][package:]type:name".
Example
This example will take you through simple steps to show how to create your own Android
application using Relative Layout. Follow the following steps to modify the Android application
we created in Hello World Example chapter –
Step Description
1 You will use Android Studio IDE to create an Android application and name it as demo
under a package com.example.demo as explained in the Hello World Example chapter.
2 Modify the default content of res/layout/activity_main.xml file to include few widgets
in Relative layout.
3 Define required constants in res/values/strings.xml file
4 Run the application to launch Android emulator and verify the result of the changes
This example will take you through simple steps to show how to create your own Android
application using Table Layout. Follow the following steps to modify the Android application
we created in Hello World Example chapter
Example
− Step Description
1 You will use Android Studio IDE to create an Android application and name it as demo
under a package com.example.demo as explained in the Hello World Example chapter.
2 Modify the default content of res/layout/activity_main.xml file to include few widgets
in table layout.
3 No need to modify string.xml, Android studio takes care of default constants
4 Run the application to launch Android emulator and verify the result of the changes
done in the application.
<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textClock"
android:layout_column="2" />
</TableRow>
<TableRow>
<TextView
android:text="First Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="200px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView
android:text="Last Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:width="100px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ratingBar"
android:layout_column="2" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="@+id/button"
android:layout_column="2" />
</TableRow>
</TableLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>
Android Absolute Layout
An Absolute Layout lets you specify exact locations (x/y coordinates) of its children. Absolute
layouts are less flexible and harder to maintain than other types of layouts without absolute
positioning.
Absolute Layout
AbsoluteLayout Attributes
Following are the important attributes specific to AbsoluteLayout –
Example
This example will take you through simple steps to show how to create your own Android
application using absolute layout. Follow the following steps to modify the Android application
we created in Hello World Example chapter –
is the content of the modified main activity file src/com.example.demo/MainActivity.java.
This file can include each of the fundamental lifecycle methods.
package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Following will be the content of res/layout/activity_main.xml file −
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="OK"
android:layout_x="50px"
android:layout_y="361px" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_x="225px"
android:layout_y="361px" />
</AbsoluteLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">demo</string>
<string name="action_settings">Settings</string>
</resources>
Android Frame Layout
Frame Layout is designed to block out an area on the screen to display a single item.
Generally, FrameLayout should be used to hold a single child view, because it can be difficult
to organize child views in a way that's scalable to different screen sizes without the children
overlapping each other.
You can, however, add multiple children to a FrameLayout and control their position within
the FrameLayout by assigning gravity to each child, using the android:layout_gravity attribute.
FrameLayout Attributes
Following are the important attributes specific to FrameLayout –
The ListView and GridView are subclasses of AdapterView and they can be populated by
binding them to an Adapter, which retrieves data from an external source and creates a View
that represents each data entry.
Android provides several subclasses of Adapter that are useful for retrieving different kinds of
data and building views for an AdapterView ( i.e. ListView or GridView). The common adapters
are ArrayAdapter,Base Adapter, CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and
WrapperListAdapter. We will see separate examples for both the adapters.
ListView Attributes
1 android:id
2 android:divider
3 android:dividerHeight
This specifies height of the divider. This could be in px, dp, sp, in, or mm.
4 android:entries
Specifies the reference to an array resource that will populate the ListView.
5 android:footerDividersEnabled
When set to false, the ListView will not draw the divider before each footer view. The
default value is true.
6 android:headerDividersEnabled
When set to false, the ListView will not draw the divider after each header view. The
default value is true.
ArrayAdapter
You can use this adapter when your data source is an array. By default, ArrayAdapter creates a
view for each array item by calling toString() on each item and placing the contents in a
TextView. Consider you have an array of strings you want to display in a ListView, initialize a
new ArrayAdapter using a constructor to specify the layout for each string and the string array
−
First argument this is the application context. Most of the case, keep it this.
Second argument will be layout defined in XML file and having TextView for each string in
the array.
Final argument is an array of strings which will be populated in the text view.
Once you have array adapter created, then simply call setAdapter() on your ListView object as
follows −
listView.setAdapter(adapter);
You will define your list view under res/layout directory in an XML file. For our example we are
going to using activity_main.xml file.
package com.example.ListDisplay;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
// Array of strings...
"WebOS","Ubuntu","Windows7","Max OS X"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
R.layout.activity_listview, mobileArray);
listView.setAdapter(adapter);
<LinearLayout 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:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
<resources>
<string name="app_name">ListDisplay</string>
<string name="action_settings">Settings</string>
</resources>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
Android Grid View
Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the
grid items are not necessarily predetermined but they automatically inserted to the layout
using a ListAdapter
Grid view
An adapter actually bridges between UI components and the data source that fill data into UI
Component. Adapter can be used to supply the data to like spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by
binding them to an Adapter, which retrieves data from an external source and creates a View
that represents each data entry.
GridView Attributes
1 android:id
2 android:columnWidth
This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm.
3 android:gravity
Specifies the gravity within each cell. Possible values are top, bottom, left, right, center,
center_vertical, center_horizontal etc.
4 android:horizontalSpacing
Defines the default horizontal spacing between columns. This could be in px, dp, sp, in,
or mm.
5 android:numColumns
Defines how many columns to show. May be an integer value, such as "100" or auto_fit
which means display as many columns as possible to fill the available space.
6 android:stretchMode
Defines how columns should stretch to fill the available empty space, if any. This must
be either of the values −
7 android:verticalSpacing
Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or
mm.
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.GridView;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview.setAdapter(new ImageAdapter(this));
}
}
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>
package com.example.helloworld;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
// Constructor
public ImageAdapter(Context c) {
mContext = c;
return mThumbIds.length;
return null;
return 0;
ImageView imageView;
if (convertView == null) {
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
else
imageView.setImageResource(mThumbIds[position]);
return imageView;
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
};
One important aspect to consider is how to support multiple screens in Android. As we know,
Android is an operating system installed on many devices. One of the most important
consequences is that the developer has to face with different screen resolution and densities.
There are, on the market, many devices with different capabilities in terms of resolution and
density and as developer we have to take it into account in order to create an application that
can have a good usability in all these devices. You can think that an android application can be
executed on a smart phone and on a tablet and it should be clear the screen size differences.
Before digging into the details how to support multiple screen sizes and densities it is
important that we clarify some terms:
– Resolution: is the number of pixels on the device screen. It can be for example 480×800 etc.
– Density: is the number of pixel in a specific area. Usually we consider dot per inch (dpi). This
is a measure of the screen quality
Orientation: is how the screen is oriented. It can assume two different values: Landscape and
Portrait
Using these concepts we can create apps that support multiple screens. There are two
different aspects that we have to consider when we want to support multiple screens in
Android: one is how we place object into the screen and we define it as layout and the second
is the images. The first aspect has to do with resolution because we can have more or less
space to place our components the second has to do with image resolution. Android has a
smart way to handle different layout for different screen size and different image resolutions
for different screen density.
If we want to support all these screen sizes we have to map these android names into a
directory structure inside the res directory. The convention used by android is the add these
name at the end of layout word. For example layout-small, layout-normal etc. So inside res
directory we will have a structure like this one:
As you can see all names are mapped in this structure except normal. Normal is the default
layout so it isn’t mapped with its name but just with layout. Now let’s see what is inside each
directory.
As you can see each directory contains the same elements with all the same names. The only
thing that changes is the content of each element.
For example, if we open one of these files (main.xml) in these two directories you will have:
By now we considered only the screen size but as we said earlier there are different densities
too. Density affects primary the images so an image could be the right size one a screen device
and looks too small in another device with more density.
So we have to consider this problem. Android groups devices in categories based on their
screen density, so we have:
As we did for layouts we can built a directory structure under the directory res that maps
these names. This time we don’t use layout but instead drawable.
Create UI Controls
Input controls are the interactive components in your app's user interface. Android provides a
wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check
box, zoom buttons, toggle buttons, and many more.
As explained in previous chapter, a view object may have a unique ID assigned to it which will
identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/text_id"
To create a UI Control/View/Widget you will have to define a view/widget in the layout file
and assign it a unique ID as follows −
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
</LinearLayout>
Then finally create an instance of the Control object and capture it from the layout, use the
following −
Here, we are going to create two textfields and one button for sum of two numbers. If user
clicks button, sum of two input values is displayed on the Toast.
First of all, drag 2 textfields from the Text Fields palette and one button from the Form
Widgets palette as shown in the following figure.
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:ems="10" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="34dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/Button" />
</RelativeLayout>
Activity class
File: MainActivity.java
package com.example.sumof2numbers;
import android.os.Bundle;
import android.widget.Toast;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
edittext1=(EditText)findViewById(R.id.editText1);
edittext2=(EditText)findViewById(R.id.editText2);
buttonSum=(Button)findViewById(R.id.button1);
buttonSum.setOnClickListener(new OnClickListener(){
@Override
String value1=edittext1.getText().toString();
String value2=edittext2.getText().toString();
int a=Integer.parseInt(value1);
int b=Integer.parseInt(value2);
int sum=a+b;
Toast.makeText(getApplicationContext(),String.valueOf(sum),Toast.LENGTH_LONG).show();
});
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}}
Android Toast Example
Andorid Toast can be used to display information for the short period of time. A toast contains
message to be displayed quickly and disappears after sometime.
You can also create custom toast as well for example toast displaying image. You can visit next
page to see the code for custom toast.
Toast class
Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.
There are only 2 constants of Toast class which are given below.
Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.
public static final int LENGTH_SHORT displays view for the short duration of time.
Method Description
public static Toast makeText(Context makes the toast containing text and duration.
context, CharSequence text, int duration)
public void show() displays toast.
public void setMargin (float changes the horizontal and vertical margin difference.
horizontalMargin, float verticalMargin)
Method Description
CharSequence getTextOff() Returns the text when button is not in the checked
state.
CharSequence getTextOn() Returns the text for when button is in the checked
state.
void setChecked(boolean checked) Changes the checked state of this button.
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
RadioGroup rg1;
RadioButton rb1;
Button b1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerRadioButton();
}
private void addListenerRadioButton() {
rg1 = (RadioGroup) findViewById(R.id.radioGroup);
b1 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selected=rg1.getCheckedRadioButtonId();
rb1=(RadioButton)findViewById(selected);
Toast.makeText(MainActivity.this,rb1.getText(),Toast.LENGTH_LONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of Radio Button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="ClickMe"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/imageButton"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2">
<RadioButton
android:layout_width="142dp"
android:layout_height="wrap_content"
android:text="JAVA"
android:id="@+id/radioButton"
android:textSize="25dp"
android:textColor="@android:color/holo_red_light"
android:checked="false"
android:layout_gravity="center_horizontal" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ANDROID"
android:id="@+id/radioButton2"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textColor="@android:color/holo_red_dark"
android:textSize="25dp" />
<RadioButton
android:layout_width="136dp"
android:layout_height="wrap_content"
android:text="HTML"
android:id="@+id/radioButton3"
android:layout_gravity="center_horizontal"
android:checked="false"
android:textSize="25dp"
android:textColor="@android:color/holo_red_dark" />
</RadioGroup>
</RelativeLayout>
Android - EditText Control
A EditText is an overlay over TextView that configures itself to be editable. It is the
predefined subclass of TextView that includes rich editing capabilities.
EditText Attributes: Inherited from android.widget.TextView Class −
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText eText;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eText = (EditText) findViewById(R.id.edittext);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG);
msg.show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="18dp"
android:text="@string/example_edittext" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="130dp"
android:text="@string/show_the_text" />
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text" android:inputType="text" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">demo</string>
<string name="example_edittext">Example showing EditText</string>
<string name="show_the_text">Show the Text</string>
<string name="enter_text">text changes</string>
</resources>
Android - Date Picker
Android Date Picker allows you to select the date consisting of day, month and year in
your custom user interface. For this functionality android provides DatePicker and
DatePickerDialog components.
In this tutorial, we are going to demonstrate the use of Date Picker through
DatePickerDialog. DatePickerDialog is a simple dialog containing DatePicker.
In order to show DatePickerDialog , you have to pass the DatePickerDialog id to
showDialog(id_of_dialog) method. Its syntax is given below −
showDialog(999);
On calling this showDialog method, another method called onCreateDialog gets
automatically called. So we have to override that method too. Its syntax is given below −
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
In the last step, you have to register the DatePickerDialog listener and override its
onDateSet method. This onDateSet method contains the updated day, month and year. Its
syntax is given below −
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// arg1 = year
// arg2 = month
// arg3 = day
}
};
Example:
Now you can see that the date has already been set at the bottom label. Now we will change
the date through DatePickerDialog by pressing the Set Date button. On pressing the button
following screen would appear
Now set the required date, and after setting the date, press the Done button. This dialog will
disappear and your newly setted date will start showing at the screen. This is shown below.
Android - Time Picker
Android Time Picker allows you to select the time of day in either 24 hour or AM/PM
mode. The time consists of hours, minutes and clock format. Android provides this
functionality through TimePicker class.
In order to use TimePicker class, you have to first define the TimePicker component in
your activity.xml. It is define as below −
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
After that you have to create an object of TimePicker class and get a reference of the
above defined xml component. Its syntax is given below.
import android.widget.TimePicker;
private TimePicker timePicker1;
timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
In order to get the time selected by the user on the screen, you will use getCurrentHour()
and getCurrentMinute() method of the TimePicker Class. Their syntax is given below.
int hour = timePicker1.getCurrentHour();
int min = timePicker1.getCurrentMinute();
Apart form these methods, there are other methods in the API that gives more control
over TimePicker Component. They are listed below.
Sr.No Method & description
1 is24HourView()
This method returns true if this is in 24 hour view else false
2 isEnabled()
This method returns the enabled status for this view
3 setCurrentHour(Integer currentHour)
This method sets the current hour
4 setCurrentMinute(Integer currentMinute)
This method sets the current minute
5 setEnabled(boolean enabled)
This method set the enabled state of this view
6 setIs24HourView(Boolean is24HourView)
This method set whether in 24 hour or AM/PM mode
7 setOnTimeChangedListener(TimePicker.OnTimeChangedLis
tener onTimeChangedListener)
This method Set the callback that indicates the time has been
adjusted by the user
Example:
android.app.ProgressDialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button b1;
private ProgressDialog progress;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button2);
}
public void download(View view){
progress=new ProgressDialog(this);
progress.setMessage("Downloading Music");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.setProgress(0);
progress.show();
final int totalProgressTime = 100;
final Thread t = new Thread() {
@Override
public void run() {
int jumpTime = 0;
while(jumpTime < totalProgressTime) {
try {
sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();
}
}
Modify the content of res/layout/activity_main.xml to the following −
<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=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Progress bar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download"
android:onClick="download"
android:id="@+id/button2"
android:layout_marginLeft="125dp"
android:layout_marginStart="125dp"
android:layout_centerVertical="true" />
</RelativeLayout>
Android List View
Android ListView is a view which groups several items and display them in vertical
scrollable list. The list items are automatically inserted to the list using an Adapter
that pulls content from a source such as an array or database.
LIST VIEW
An adapter actually bridges between UI components and the data source that fill
data into UI Component. Adapter holds the data and send the data to adapter
view, the view can takes the data from adapter view and shows the data on
different views like as spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be
populated by binding them to an Adapter, which retrieves data from an external
source and creates a View that represents each data entry.
Android provides several subclasses of Adapter that are useful for retrieving
different kinds of data and building views for an AdapterView ( i.e. ListView or
GridView). The common adapters are ArrayAdapter,Base Adapter,CursorAdapter,
SimpleCursorAdapter,SpinnerAdapter and WrapperListAdapter. We will see
separate examples for both the adapters.
ListView Attributes
Following are the important attributes specific to GridView –
Sr.No Attribute & Description
1 android:id
This is the ID which uniquely identifies the layout.
2 android:divider
This is drawable or color to draw between list items.
3 android:dividerHeight
This specifies height of the divider. This could be in px, dp, sp, in, or mm.
4 android:entries
Specifies the reference to an array resource that will populate the ListView.
5 android:footerDividersEnabled
When set to false, the ListView will not draw the divider before each footer
view. The default value is true.
6 android:headerDividersEnabled
When set to false, the ListView will not draw the divider after each header view.
The default value is true.
ArrayAdapter
You can use this adapter when your data source is an array. By default,
ArrayAdapter creates a view for each array item by calling toString() on each item
and placing the contents in a TextView. Consider you have an array of strings you
want to display in a ListView, initialize a new ArrayAdapter using a constructor to
specify the layout for each string and the string array −
ArrayAdapter adapter = new
ArrayAdapter<String>(this,R.layout.ListView,StringArray);
Here are arguments for this constructor −
First argument this is the application context. Most of the case, keep it this.
Second argument will be layout defined in XML file and having TextView for
each string in the array.
Final argument is an array of strings which will be populated in the text view.
Once you have array adapter created, then simply call setAdapter() on your
ListView object as follows –
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
You will define your list view under res/layout directory in an XML file. For our
example we are going to using activity_main.xml file.
Example
Following is the example which will take you through simple steps to show how to
create your own Android application using ListView.
package com.example.ListDisplay;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListDisplay extends Activity {
// Array of strings...
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
"WebOS","Ubuntu","Windows7","Max OS X"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, mobileArray);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
}
}
Following will be the content of res/layout/activity_main.xml file −
<LinearLayout 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:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Following will be the content of res/values/strings.xml to define two new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ListDisplay</string>
<string name="action_settings">Settings</string>
</resources>
Following will be the content of res/layout/activity_listview.xml file −
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
onKey() OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a
hardware key on the device. You will use onKey() event handler to handle such
event.
onTouch() OnTouchListener()
This is called when the user presses the key, releases the key, or any movement
gesture on the screen. You will use onTouch() event handler to handle such event.
onMenuItemClic OnMenuItemClickListener()
k() This is called when the user selects a menu item. You will use onMenuItemClick()
event handler to handle such event.
onCreateContext onCreateContextMenuItemListener()
Menu() This is called when the context menu is being built(as the result of a sustained "long
click)
There are many more event listeners available as a part of View class like
OnHoverListener, OnDragListener etc which may be needed for your application.
So I recommend to refer official documentation for Android application
development in case you are going to develop a sophisticated apps.
Event Listeners Registration
Event Registration is the process by which an Event Handler gets registered with
an Event Listener so that the handler is called when the Event Listener fires the
event. Though there are several tricky ways to register your event listener for any
event, but I'm going to list down only top 3 ways, out of which you can use any of
them based on the situation.
Using an Anonymous Inner Class
Activity class implements the Listener interface.
Using Layout file activity_main.xml to specify event handler directly.
Below section will provide you detailed examples on all the three scenarios −
Touch Mode
Users can interact with their devices by using hardware keys or buttons or
touching the screen.Touching the screen puts the device into touch mode. The
user can then interact with it by touching the on-screen virtual buttons, images,
etc.You can check if the device is in touch mode by calling the View class’s
isInTouchMode() method.
Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in
focus. This indicates that it’s ready to accept input from the user.
isFocusable() − it returns true or false
isFocusableInTouchMode() − checks to see if the view is focusable in touch
mode. (A view may be focusable when using a hardware key but not when the
device is in touch mode)
android:foucsUp="@=id/button_l"
onTouchEvent()
public boolean onTouchEvent(motionEvent event){
switch(event.getAction()){
case TOUCH_DOWN:
Toast.makeText(this,"you have clicked down Touch
button",Toast.LENTH_LONG).show();
break();
case TOUCH_UP:
Toast.makeText(this,"you have clicked up touch
button",Toast.LENTH_LONG).show();
break;
case TOUCH_MOVE:
Toast.makeText(this,"you have clicked move touch
button"Toast.LENTH_LONG).show();
break;
}
return super.onTouchEvent(event) ;
}
Event Handling Examples
Event Listeners Registration Using an Anonymous Inner Class
Here you will create an anonymous implementation of the listener and will be
useful if each class is applied to a single control only and you have advantage to
pass arguments to event handler. In this approach event handler methods can
access private data of Activity. No reference is needed to call to Activity.
But if you applied the handler to more than one control, you would have to cut
and paste the code for the handler and if the code for the handler is long, it makes
the code harder to maintain.
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private ProgressDialog progress;
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(25);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(55);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Handling "
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>
<TextView
android:id="@+id/textView2"
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android - list Fragment
Static library support version of the framework's ListFragment. Used to write apps
that run on platforms prior to Android 3.0. When running on Android 3.0 or above,
this implementation is still used.
The basic implementation of list fragment is for creating list of items in
fragments
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ListFragmentDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</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>
Following will be the content of res/layout/activity_main.xml file. it contained
linear layout and fragment tag.
<?xml version="1.0" encoding="utf-8"?>
<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>
Following will be the content of res/layout/list_fragment.xml file. it contained
linear layout,list view and text view
<?xml version="1.0" encoding="utf-8"?>
<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>
following will be the content of src/main/java/myListFragment.java file.before
writing to code, need to follow few steps as shown below
Create a class MyListFragment and extend it to ListFragment.
Inside the onCreateView() method , inflate the view with above defined
list_fragment xml layout.
Inside the onActivityCreated() method , create a arrayadapter from resource ie
using String array R.array.planet which you can find inside the string.xml and set
this adapter to listview and also set the onItem click Listener.
Inside the OnItemClickListener() method , display a toast message with Item name
which is being clicked.
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;
public class MyListFragment extends ListFragment implements
OnItemClickListener {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.Planets, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
}
Following code will be the content of MainActivity.java
package com.example.tutorialspoint7.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
following code will be the content of manifest.xml, which has placed at
res/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<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>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>