0% found this document useful (0 votes)
39 views102 pages

UNIT II Android UI Design

This document covers Android UI design, focusing on basic UI components like fragments, layouts, and event handling. It explains the fragment lifecycle, how to create and manage fragments, and the various types of layouts available in Android. Additionally, it provides examples of XML layout files and their attributes, emphasizing the importance of view identification and layout parameters.

Uploaded by

Manisha Rathod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views102 pages

UNIT II Android UI Design

This document covers Android UI design, focusing on basic UI components like fragments, layouts, and event handling. It explains the fragment lifecycle, how to create and manage fragments, and the various types of layouts available in Android. Additionally, it provides examples of XML layout files and their attributes, emphasizing the importance of view identification and layout parameters.

Uploaded by

Manisha Rathod
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 102

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.

onResume()Fragment becomes active.


 onPause() The system calls this method as the first indication that the user is leaving the
fragment. This is usually where you should commit any changes that should be persisted
beyond the current user session.
 onStop()Fragment going to be stopped by calling onStop()
 onDestroyView()Fragment view will destroy after call this method
 onDestroy()onDestroy() called to do final clean up of the fragment's state but Not
guaranteed to be called by the Android platform.
How to use Fragments?
This involves number of simple steps to create Fragments.
 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.

Android Fragment Example


Let's have a look at the simple example of android fragment.
activity_main.xml
File: activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="@+id/fragment2"
android:name="com.example.fragmentexample.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/fragment1"
android:name="com.example.fragmentexample.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
File: fragment1.xml
<?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"
android:background="#00ff00" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fragment frist"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
File: fragment2.xml
<?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"
android:background="#0000ff"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Fragment"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
MainActivity class
File: MainActivity.java
package com.example.fragmentexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
File: Fragment1.java
package com.example.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment1,container, false);
}
}
File: Fragment2.java
package com.example.fragmentexample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment2,container, false);
}
}
Output:
Android - UI Layouts
The basic building block for user interface is a View object which is created from the View
class and occupies a rectangular area on the screen and is responsible for drawing and event
handling. View is the base class for widgets, which are used to create interactive UI
components like buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold other Views or
other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either at
run time using View/ViewGroup objects or you can declare your layout using simple XML file
main_layout.xml which is located in the res/layout folder of your project.
LAYOUT PARAMS
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout
may contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a
simple example of XML file having LinearLayout:
<?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" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />
<!-- More GUI components go here -->
</LinearLayout>
Once your layout has created, you can load the layout resource from your application code, in
your Activity.onCreate() callback implementation as shown below −
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Android Layout Types :
There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.

Sr.No Layout & Description


1 Linear Layout
LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally.
2 Relative Layout
RelativeLayout is a view group that displays child views in relative positions.
3 Table Layout
TableLayout is a view that groups views into rows and columns.
4 Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.
5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a single view.
6 List View
ListView is a view group that displays a list of scrollable items.
7 Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

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.

Constant Value Description


top 0x30 Push object to the top of its
container, not changing its size.
bottom 0x50 Push object to the bottom of its
container, not changing its size.
left 0x03 Push object to the left of its
container, not changing its size.
right 0x05 Push object to the right of its
container, not
changing its
size.
center_vertical 0x10 Place object in the vertical center of
its container, not changing its size.
fill_vertical 0x70 Grow the vertical size of the object if
needed so it completely fills its
container.
center_horizontal 0x01 Place object in the horizontal center
of its container, not changing its size.
fill_horizontal 0x07 Grow the horizontal size of the object
if needed so it completely fills its
container.
center 0x11 Place the object in the center of its
container in both the vertical and
horizontal axis, not changing its size.
fill 0x77 Grow the horizontal and vertical size
of the object if needed so it
completely fills its container.
clip_vertical 0x80 Additional option that can be set to
have the top and/or bottom edges of
the child clipped to its container's
bounds. The clip will be based on the
vertical gravity: a top gravity will clip
the bottom edge, a bottom gravity
will clip the top edge, and neither will
clip both edges.
clip_horizontal 0x08 Additional option that can be set to
have the left and/or right edges of the
child clipped to its container's
bounds. The clip will be based on the
horizontal gravity: a left gravity will
clip the right edge, a right gravity will
clip the left edge, and neither will clip
both edges.
start 0x00800003 Push object to the beginning of its
container, not changing its size.
end 0x00800005 Push object to the end of its
container, not changing its size.

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.

Android Linear Layout


Android LinearLayout is a view group that aligns all children in either vertically or horizontally.
Linear Layout
LinearLayout Attributes
Following are the important attributes specific to LinearLayout –

Sr.No Attribute & Description


1 android:id
This is the ID which uniquely identifies the layout.
2 android:baselineAligned
This must be a boolean value, either "true" or "false" and prevents the layout from
aligning its children's baselines.
3 android:baselineAlignedChildIndex
When a linear layout is part of another layout that is baseline aligned, it can specify
which of its children to baseline align.
4 android:divider
This is drawable to use as a vertical divider between buttons. You use a color value, in
the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
5 android:gravity
This specifies how an object should position its content, on both the X and Y axes.
Possible values are top, bottom, left, right, center, center_vertical, center_horizontal
etc.
6 android:orientation
This specifies the direction of arrangement and you will use "horizontal" for a row,
"vertical" for a column. The default is horizontal.
7 android:weightSum :
Sum up of child weight

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 –

Sr.No. Attribute & Description


1 android:id
This is the ID which uniquely identifies the layout.
2 android:gravity
This specifies how an object should position its content, on both the X and Y axes.
Possible values are top, bottom, left, right, center, center_vertical, center_horizontal
etc.
3 android:ignoreGravity
This indicates what view should not be affected by gravity.

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

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 −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentStart="true"
android:layout_below="@+id/name">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button2" />
</LinearLayout>
</RelativeLayout>
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="action_settings">Settings</string>
<string name="reminder">Enter your name</string>
</resources>
Android Table Layout
Android TableLayout going to be arranged groups of views into rows and columns. You will use
the <TableRow> element to build a row in the table. Each row has zero or more cells; each cell
can hold one View object.
TableLayout containers do not display border lines for their rows, columns, or cells.
TableLayout Attributes
Following are the important attributes specific to TableLayout –

Sr.No Attribute & Description


.
1 android:id
This is the ID which uniquely identifies the layout.
2 android:collapseColumns
This specifies the zero-based index of the columns to collapse. The column
indices must be separated by a comma: 1, 2, 5.
3 android:shrinkColumns
The zero-based index of the columns to shrink. The column indices must be
separated by a comma: 1, 2, 5.
4 android:stretchColumns
The zero-based index of the columns to stretch. The column indices must
be separated by a comma: 1, 2, 5.

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 –

Sr.No Attribute & Description


1 android:id
This is the ID which uniquely identifies the layout.
2 android:layout_x
This specifies the x-coordinate of the view.
3 android:layout_y
This specifies the y-coordinate of the view.

Public Constructors AbsoluteLayout(Context context)


AbsoluteLayout(Context context, AttributeSet attrs)
AbsoluteLayout(Context context, AttributeSet attrs, int defStyleAttr)
AbsoluteLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

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 –

Sr. Attribute & Description


N
o
1 android:id
This is the ID which uniquely identifies the layout.
2 android:foreground
This defines the drawable to draw over the content and possible values may be a color
value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
3 android:foregroundGravity
Defines the gravity to apply to the foreground drawable. The gravity defaults to fill.
Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc.
4 android:measureAllChildren
Determines whether to measure all children or just those in the VISIBLE or INVISIBLE state
when measuring. Defaults to false.
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 −
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:src="@drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_height="250px"
android:layout_width="250px"/>
<TextView
android:text="Frame Demo"
android:textSize="30px"
android:textStyle="bold"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
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 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. Attribute & Description
No

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.

Following is the content of the modified main activity file


src/com.example.ListDisplay/ListDisplay.java. This file can include each of the fundamental
life cycle methods.

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>
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

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: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 −

 none − Stretching is disabled.


 spacingWidth − The spacing between each column is stretched.

 columnWidth − Each column is stretched equally.

 spacingWidthUniform − The spacing between each column is uniformly stretched..

7 android:verticalSpacing

Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or
mm.

Following is the content of the modified main activity file


src/com.example.helloworld/MainActivity.java. This file can include each of the fundamental
lifecycle methods.

package com.example.helloworld;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.widget.GridView;

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

GridView gridview = (GridView) findViewById(R.id.gridview);

gridview.setAdapter(new ImageAdapter(this));

}
}

Following will be the content of res/layout/activity_main.xml file −

<?xml version="1.0" encoding="utf-8"?>

<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"

/>

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>

Following will be the content of src/com.example.helloworld/ImageAdapter.java file −

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;

public class ImageAdapter extends BaseAdapter {

private Context mContext;

// Constructor

public ImageAdapter(Context c) {

mContext = c;

public int getCount() {

return mThumbIds.length;

public Object getItem(int position) {

return null;

public long getItemId(int position) {

return 0;

// create a new ImageView for each item referenced by the Adapter

public View getView(int position, View convertView, ViewGroup parent) {

ImageView imageView;
if (convertView == null) {

imageView = new ImageView(mContext);

imageView.setLayoutParams(new GridView.LayoutParams(85, 85));

imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

imageView.setPadding(8, 8, 8, 8);

else

imageView = (ImageView) convertView;

imageView.setImageResource(mThumbIds[position]);

return imageView;

// Keep all Images in array

public Integer[] mThumbIds = {

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

};

Multiple screen sizes

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.

From (inch) To (inch) Android


name
2 4 small
around 4 around 4 normal
from around 7 large
4
7 10 xlarge

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:

Android multiple screen: Screen Density

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:

Density Android name

Small around 120dpi (ldpi)

Normal around 160dpi (mdpi)

High around 240dpi (hdpi)

x-High around 320dpi (xhdpi)

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 −

<?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" >

<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="I am a TextView" />

</LinearLayout>

Then finally create an instance of the Control object and capture it from the layout, use the
following −

TextView myText = (TextView) findViewById(R.id.text_id);

Android Button Example

Android Button represents a push-button. The android.widget.Button is subclass of TextView


class and CompoundButton is the subclass of Button class.

There are different types of buttons in android such as RadioButton, ToggleButton,


CompoundButton etc.

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.

Drag the component or write the code for UI in activity_main.xml

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.

The generated code for the ui components will be like this:


File: activity_main.xml

<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

Now write the code to display the sum of two numbers.

File: MainActivity.java

package com.example.sumof2numbers;

import android.os.Bundle;

import android.widget.Toast;

public class MainActivity extends Activity {

private EditText edittext1,edittext2;

private Button buttonSum;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

addListenerOnButton();
}

public void addListenerOnButton(){

edittext1=(EditText)findViewById(R.id.editText1);

edittext2=(EditText)findViewById(R.id.editText2);

buttonSum=(Button)findViewById(R.id.button1);

buttonSum.setOnClickListener(new OnClickListener(){

@Override

public void onClick(View view) {

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

public boolean onCreateOptionsMenu(Menu menu) {

// 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.

The android.widget.Toast class is the subclass of java.lang.Object class.

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.

Constants of Toast class

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.

Methods of Toast class


The widely used methods of Toast class are given below.

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)

Android Toast Example


Toast.makeText(getApplicationContext(),"Hello ",Toast.LENGTH_SHORT).show();
Another code:
Toast toast=Toast.makeText(getApplicationContext(),"Hello ",Toast.LENGTH_SHORT);
toast.setMargin(50,50);
toast.show();
Here, getApplicationContext() method returns the instance of Context.
Full code of activity class displaying Toast
Let's see the code to display the toast.
File: MainActivity.java
package com.example.toast;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}}
Android ToggleButton Example:
Android Toggle Button can be used to display checked/unchecked (On/Off) state on the
button.
It is beneficial if user have to change the setting between two states. It can be used to On/Off
Sound, Wifi, Bluetooth etc.
Since Android 4.0, there is another type of toggle button called switch that provides slider
control.
Android ToggleButton and Switch both are the subclasses of CompoundButton class.
Android ToggleButton class
ToggleButton class provides the facility of creating the toggle button.
XML Attributes of ToggleButton class
The 3 XML attributes of ToggleButton class.
XML Attribute Description
android:disabledAlpha The alpha to apply to the indicator when disabled.
android:textOff The text for the button when it is not checked.
android:textOn The text for the button when it is checked.
Methods of ToggleButton class
The widely used methods of ToggleButton class are given below.

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.

Android ToggleButton Example


activity_main.xml
Drag two toggle button and one button for the layout. Now the activity_main.xml file will look
like this:
File: activity_main.xml
<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" >
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="60dp"
android:layout_marginTop="18dp"
android:text="ToggleButton1"
android:textOff="Off"
android:textOn="On" />
<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/toggleButton1"
android:layout_alignBottom="@+id/toggleButton1"
android:layout_marginLeft="44dp"
android:layout_toRightOf="@+id/toggleButton1"
android:text="ToggleButton2"
android:textOff="Off"
android:textOn="On" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/toggleButton2"
android:layout_marginTop="82dp"
android:layout_toRightOf="@+id/toggleButton1"
android:text="submit" />
</RelativeLayout>
Activity class
Let's write the code to check which toggle button is ON/OFF.
File: MainActivity.java
package com.example.togglebutton;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private ToggleButton toggleButton1, toggleButton2;
private Button buttonSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){
//Getting the ToggleButton and Button instance from the layout xml file
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton1);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
buttonSubmit=(Button)findViewById(R.id.button1);
//Performing action on button click
buttonSubmit.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
StringBuilder result = new StringBuilder();
result.append("ToggleButton1 : ").append(toggleButton1.getText());
result.append("\nToggleButton2 : ").append(toggleButton2.getText());
//Displaying the message in toast
Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}}
Android Spinner Example
Android Spinner is like the combo box of AWT or Swing. It can be used to display the multiple
options to the user in which only one item can be selected by the user.
Android spinner is like the drop down menu with multiple values from which the end user can
select only one value.
Android spinner is associated with AdapterView. So you need to use one of the adapter
classes with spinner.
Android Spinner class is the subclass of AsbSpinner class.
In this example, we are going to display the country list. You need to use ArrayAdapter class
to store the country list.
Let's see the simple example of spinner in android.
activity_main.xml
Drag the Spinner from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
<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" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />
</RelativeLayout>
Activity class
Let's write the code to display item on the spinner and perform event handling.
File: MainActivity.java
package com.example.spinner;
import android.widget.Spinner;
public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener {
String[] country = { "India", "USA", "China", "Japan", "Other", };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.spinner1);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the country list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Android - CheckBox Control


A CheckBox is an on/off switch that can be toggled by the user. You should use check-boxes
when presenting users with a group of selectable options that are not mutually exclusive.
CheckBox Attributes
Following are the important attributes related to CheckBox control. You can check Android
official documentation for complete list of attributes and related methods which you can use
to change these attributes are run time.
Inherited from android.widget.TextView Class –
Sr.No Attribute & Description
1 android:autoText
If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
2 android:drawableBottom
This is the drawable to be drawn below the text.
3 android:drawableRight
This is the drawable to be drawn to the right of the text.
4 android:editable
If set, specifies that this TextView has an input method.
5 android:text
This is the Text to display.
Inherited from android.view.View Class −
Sr.No Attribute & Description
1 android:background
This is a drawable to use as the background.
2 android:contentDescription
This defines text that briefly describes content of the view.
3 android:id
This supplies an identifier name for this view.
4 android:onClick
This is the name of the method in this View's context to invoke when the
view is clicked.
5 android:visibility
This controls the initial visibility of the view.
Example
This example will take you through simple steps to show how to create your own Android
application using Linear Layout and CheckBox.
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends Activity {
CheckBox ch1,ch2;
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ch1=(CheckBox)findViewById(R.id.checkBox1);
ch2=(CheckBox)findViewById(R.id.checkBox2);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Thanks : ").append(ch1.isChecked());
result.append("\nThanks: ").append(ch2.isChecked());
Toast.makeText(MainActivity.this, result.toString(),Toast.LENGTH_LONG).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:text="Example of checkbox"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like Tutorials Point"
android:layout_above="@+id/button"
android:layout_centerHorizontal="true" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do you like android "
android:checked="false"
android:layout_above="@+id/checkBox1"
android:layout_alignLeft="@+id/checkBox1"
android:layout_alignStart="@+id/checkBox1" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/checkBox1"
android:layout_below="@+id/textView1" android:layout_marginTop="39dp"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/checkBox1"
android:layout_alignStart="@+id/checkBox1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
<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" />
</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">MyApplication</string>
</resources>

Android - RadioButton Control


A RadioButton has two states: either checked or unchecked.This allows the user to select
one option from a set.
Example:

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 −

Sr.No Attribute & Description


1 android:autoText
If set, specifies that this TextView has a textual input method and automatically
corrects some common spelling errors.
2 android:drawableBottom
This is the drawable to be drawn below the text.
3 android:drawableRight
This is the drawable to be drawn to the right of the text.
4 android:editable
If set, specifies that this TextView has an input method.
5 android:text
This is the Text to display.
Inherited from android.view.View Class −
Sr.No Attribute & Description
1 android:background
This is a drawable to use as the background.
2 android:contentDescription
This defines text that briefly describes content of the view.
3 android:id
This supplies an identifier name for this view.
4 android:onClick
This is the name of the method in this View's context to invoke
when the view is clicked.
5 android:visibility
This controls the initial visibility of the view.
Example:

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
}
};

Sr Method & description


.N
o
1 getDayOfMonth()
This method gets the selected day of month
2 getMonth()
This method gets the selected month
3 getYear()
This method gets the selected year
4 setMaxDate(long maxDate)
This method sets the maximal date supported by this DatePicker in milliseconds
since January 1, 1970 00:00:00 in getDefault() time zone
5 setMinDate(long minDate)
This method sets the minimal date supported by this NumberPicker in milliseconds
since January 1, 1970 00:00:00 in getDefault() time zone
6 setSpinnersShown(boolean shown)
This method sets whether the spinners are shown
7 updateDate(int year, int month, int dayOfMonth)
This method updates the current date
8 getCalendarView()
This method returns calendar view
9 getFirstDayOfWeek() : This Method returns first day of the week

Example:

Following is the content of the modified main activity file


src/com.example.datepicker/MainActivity.java.
package com.example.datepicker;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateView = (TextView) findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
}
@SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca",
Toast.LENGTH_SHORT)
.show();
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}
Following is the modified content of the xml res/layout/activity_main.xml.
<?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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:onClick="setDate"
android:text="@string/date_button_set" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:text="@string/date_label_set"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="66dp"
android:layout_toLeftOf="@+id/button1"
android:text="@string/date_view_set"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button1"
android:layout_below="@+id/textView2"
android:layout_marginTop="72dp"
android:text="@string/date_selected"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">DatePicker</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="date_label_set">Press the button to set the date</string>
<string name="date_button_set">Set Date</string>
<string name="date_view_set">The Date is: </string>
<string name="date_selected"></string>
</resources>

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:

Following is the content of the modified main activity file


src/com.example.timepicker/MainActivity.java.
package com.example.timepicker;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
public class MainActivity extends Activity {
private TimePicker timePicker1;
private TextView time;
private Calendar calendar;
private String format = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
time = (TextView) findViewById(R.id.textView1);
calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int min = calendar.get(Calendar.MINUTE);
showTime(hour, min);
}
public void setTime(View view) {
int hour = timePicker1.getCurrentHour();
int min = timePicker1.getCurrentMinute();
showTime(hour, min);
}
public void showTime(int hour, int min) {
if (hour == 0) {
hour += 12;
format = "AM";
} else if (hour == 12) {
format = "PM";
} else if (hour > 12) {
hour -= 12;
format = "PM";
} else {
format = "AM";
}
time.setText(new StringBuilder().append(hour).append(" : ").append(min)
.append(" ").append(format));
}
}
Following is the modified content of the xml res/layout/activity_main.xml.
<?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/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="@string/time_pick"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/set_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="180dp"
android:onClick="setTime"
android:text="@string/time_save" />
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/set_button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="24dp" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/timePicker1"
android:layout_alignTop="@+id/set_button"
android:layout_marginTop="67dp"
android:text="@string/time_current"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="@string/time_selected"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Following is the content of the res/values/string.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TimePicker</string>
<string name="action_settings">Settings</string>
<string name="time_picker_example">Time Picker Example</string>
<string name="time_pick">Pick the time and press save button</string>
<string name="time_save">Save</string>
<string name="time_selected"></string>
<string name="time_current">The Time is:</string>
</resources>

Android Progress Bar using ProgressDialog


Progress bars are used to show progress of a task. For example, when you are uploading
or downloading something from the internet, it is better to show the progress of
download/upload to the user.
In android there is a class called ProgressDialog that allows you to create progress bar. In
order to do this, you need to instantiate an object of this class. Its syntax is.
ProgressDialog progress = new ProgressDialog(this);
Now you can set some properties of this dialog. Such as, its style, its text etc.
progress.setMessage("Downloading Music :) ");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
Sr. Title & description
No
1 getMax()
This method returns the maximum value of the progress.
2 incrementProgressBy(int diff)
This method increments the progress bar by the difference of value passed as a
parameter.
3 setIndeterminate(boolean indeterminate)
This method sets the progress indicator as determinate or indeterminate.
4 setMax(int max)
This method sets the maximum value of the progress dialog.
5 setProgress(int value)
This method is used to update the progress dialog with some specific value.
6 show(Context context, CharSequence title, CharSequence message)
This is a static method, used to display progress dialog.

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>

Android - Event Handling


Events are a useful way to collect data about a user's interaction with interactive
components of Applications. Like button presses or screen touch etc. The Android
framework maintains an event queue as first-in, first-out (FIFO) basis. You can
capture these events in your program and take appropriate action as per
requirements.
There are following three concepts related to Android Event Management −
 Event Listeners − An event listener is an interface in the View class that contains
a single callback method. These methods will be called by the Android framework
when the View to which the listener has been registered is triggered by user
interaction with the item in the UI.
 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.
 Event Handlers − When an event happens and we have registered an event
listener for the event, the event listener calls the Event Handlers, which is the
method that actually handles the event.

Event Listeners & Event Handlers:


Event Handler Event Listener & Description
onClick() OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget like
button, text, image etc. You will use onClick() event handler to handle such event.
onLongClick() OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget like
button, text, image etc. for one or more seconds. You will use onLongClick() event handler
to handle such event.
onFocusChange() OnFocusChangeListener()
This is called when the widget looses its focus ie. user goes away
from the view item. You will use onFocusChange() event handler to handle such event.

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>

You might also like