MAD Unit - 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 92

UNIT – II:

Building Blocks for Android Application Design:


Introduction to Layouts, Linear Layout, Relative Layout, Absolute Layout, Using Image View,
Frame Layout, Table Layout, Grid Layout, Adapting to Screen orientation.
Utilizing Resources and Media Resources, Creating Values Resources, Using Drawable
Resources, Switching States with Toggle Buttons, Creating an Images Switcher Application,
Scrolling Through Scroll View, playing Audio, Playing Video, Displaying Progress with Progress
Bar, Using Assets

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

MOBILE APPLICATION DEVELOPMENT 51


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

MOBILE APPLICATION DEVELOPMENT 52


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 there are other attributes which are specific
to that layout. Following are common attributes and will be applied to all the layouts:

Sr.No Attribute & Description

1 android:id
This is the ID which uniquely identifies the view.

2 android:layout_width
This is the width of the layout.

3 android:layout_height
This is the height of the layout

4 android:layout_marginTop
This is the extra space on the top side of the layout.

5 android:layout_marginBottom
This is the extra space on the bottom side of the layout.

6 android:layout_marginLeft
This is the extra space on the left side of the layout.

7 android:layout_marginRight
This is the extra space on the right side of the layout.

8 android:layout_gravity
This specifies how child Views are positioned.

9 android:layout_weight
This specifies how much of the extra space in the layout should be allocated to the View.

10 android:layout_x
This specifies the x-coordinate of the layout.

11 android:layout_y
This specifies the y-coordinate of the layout.

12 android:layout_width
This is the width of the layout.

13 android:layout_width
This is the width of the layout.

14 android:paddingLeft
This is the left padding filled for the layout.

MOBILE APPLICATION DEVELOPMENT 53


15 android:paddingRight
This is the right padding filled for the layout.

16 android:paddingTop
This is the top padding filled for the layout.

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

MOBILE APPLICATION DEVELOPMENT 54


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

Linear Layout:
Linear Layout is a simple layout used in android for layout designing. In the Linear layout
all the elements are displayed in linear fashion means all the childs/elements of a linear layout are
displayed according to its orientation. The value for orientation property can be either
horizontal or vertical.

MOBILE APPLICATION DEVELOPMENT 55


Types of Linear Layout Orientation:
There are two types of linear layout orientation

1. Vertical

2. Horizontal

As the name specified these two orientations are used to arrange there child one after the other, in
a line, either vertically or horizontally. Let‟s we describe these in detail.

1. Vertical:
In this all the child are arranged vertically in a line one after the other. In below code snippets we
have specified orientation “vertical” so the childs/views of this layout are displayed vertically.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="vertical"> <!-- Vertical Orientation set -->

<!-- Child Views(In this case 2 Button) are here -->

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button1"

android:id="@+id/button"

android:background="#358a32" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button2"

android:id="@+id/button2"

android:background="#0058b6" />

</LinearLayout>

MOBILE APPLICATION DEVELOPMENT 56


2. Horizontal:
In this all the child are arranged horizontally in a line one after the other. In below code
snippets we have specified orientation “horizontal” so the childs/views of this layout are displayed
horizontally.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="horizontal"> <!-- Horizontal Orientation set -->

<!-- Child Views(In this case 2 Button) are here -->

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button1"

android:id="@+id/button"

android:background="#358a32" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button2"

android:id="@+id/button2"

android:background="#0058b6" />

</LinearLayout>

Main Attributes In Linear Layout:


Now let‟s we discuss about the attributes that helps us to configure a linear layout and its child
controls. Some of the most important attributes you will use with linear layout include:

1. Orientation: The orientation attribute used to set the childs/views horizontally or vertically.
In Linear layout default orientation is vertical.

MOBILE APPLICATION DEVELOPMENT 57


Example: Orientation vertical:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="vertical"> <!-- Vertical Orientation set -->

<!-- Put Child Views like Button here -->

</LinearLayout>

Example: Orientation Horizontal:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="horizontal"> <!-- Horizontal Orientation set -->

<!-- Child Views are here -->

</LinearLayout>

2. Gravity: The gravity attribute is an optional attribute which is used to control the alignment
of the layout like left, right, center, top, bottom etc.
Example: We have set gravity right for linear layout. So the buttons gets align from right
side in Horizontal orientation.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="right"

android:orientation="horizontal">

<!--Button Child View Here--->

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

MOBILE APPLICATION DEVELOPMENT 58


android:text="Button2"

android:id="@+id/button2"

android:background="#0e7d0d" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Button1"

android:id="@+id/button"

android:background="#761212" />

</LinearLayout>

3. Layout_weight: The layout weight attribute specify each child control‟s relative importance
within the parent linear layout.

Example: weight property for button in linear layout. In the below example one button is of
weight 2 and other is of weight 1.

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

<!--Add Child View Here--->

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Weight 2"

android:background="#761212"
MOBILE APPLICATION DEVELOPMENT 59
android:layout_margin="5dp"

android:id="@+id/button"

android:layout_weight="2" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="#761212"

android:layout_margin="5dp"

android:layout_weight="1"

android:text="Weight 1" />

</LinearLayout>

In the layout image you can notice Button with weight 2 gets more size related the other.

4. Weight Sum: WeightSum is the sum up of all the child attributes weight. This attribute is
required if we define weight property of the childs.

Example: In the same above example of weight, we can define weightSum value 3.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:weightSum="3"

android:orientation="horizontal">

<!--Add Child View Here--->

</LinearLayout>

Example of Linear Layout:


Now let‟s design 2 linear layout UI. First we have designed using weight attribute and second
without using it. So below layout output will clear the difference between them:

MOBILE APPLICATION DEVELOPMENT 60


Example 1: First we will design Android Linear Layout without using weight property
In this example we have used one TextView and 4 Button. The orientation is set to vertical.
Below is the code of activity_main.xml
<!-- Vertical Orientation is set -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<!-- Text Displayed At Top -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:text="Linear Layout (Without Weight)"

android:id="@+id/textView"

android:layout_gravity="center_horizontal" />

<!-- Button Used -->

<Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Button 1"

android:background="#009300" />

MOBILE APPLICATION DEVELOPMENT 61


<Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Button 2"

android:background="#e6cf00" />

<Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Button 3"

android:background="#0472f9" />

<Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Button 4"

android:background="#e100d5" />

</LinearLayout>

Example 2: In this example of linear layout we have used weight property.


Below is the code of activity_main.xml with explanation included
<!-- Vertical Orientation is set with weightSum-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="5"

MOBILE APPLICATION DEVELOPMENT 62


android:orientation="vertical">
<!-- Text Displayed At Top -->
<TextView
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:text="Linear Layout (With Weight)"

android:id="@+id/textView"

android:layout_gravity="center_horizontal"

android:layout_weight="0"/>

<!-- Button Used -->

<Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Button 1"

android:background="#009300"

android:layout_weight="1"/>

<Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Button 2"

android:background="#e6cf00"

android:layout_weight="1"/>

<Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Button 3"

android:background="#0472f9"

android:layout_weight="1"/>

MOBILE APPLICATION DEVELOPMENT 63


<Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Button 4"

android:background="#e100d5"

android:layout_weight="1"/>

</LinearLayout>

Relative Layout:
The Relative Layout is very flexible layout used in android for custom layout designing. It gives
us the flexibility to position our component/view based on the relative or sibling component‟s
position. Just because it allows us to position the component anywhere we want so it is considered
as most flexible layout. For the same reason Relative layout is the most used layout after
the Linear Layout in Android. It allow its child view to position relative to each other or relative
to the container or another container.

In Relative Layout, you can use “above, below, left and right” to arrange the component‟s
position in relation to other component.

MOBILE APPLICATION DEVELOPMENT 64


Even though Android has drag and drop system to put one component in related to other inside
relative layout. But actually in the background lots of XML properties are working which does
this task. So Android developer can design UI either using drag & drop or using XML code.
Professional developer uses both for designing UI.

Attributes of Relative layout:


Relative Layout which will be used while designing Android App UI:
1. Above: Position the bottom edge of the view above the given anchor view ID and must be a
reference of another resource in the form of id. Example, android:layout_above
=”@+id/textView” .

For example, suppose a view with id textview2 is what we want to place above another view with
id textview. Below is the code and layout image.

<!-- textView2 is placed above textView-->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:text="Text2"

android:id="@+id/textView2"

android:layout_above="@+id/textView"

android:layout_marginBottom="100dp"

android:layout_centerHorizontal="true"/>

2. AlignBottom: AlignBottom is used to makes the bottom edges of the view match the bottom
edge of the given anchor view ID and it must be a reference to another resource, in the form of id.
Example: android:layout_ alignBottom =”@+id/button1″

In the below example we have aligned a view with id textView2 Bottom of another view with id
textView. Below is the coded and layout image.

MOBILE APPLICATION DEVELOPMENT 65


<!-- textView2 alignBottom of textView -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:layout_centerHorizontal="true"

android:id="@+id/textView2"

android:layout_alignBottom="@+id/textView"

android:text="Text2 alignBottom of Text1"

android:layout_marginBottom="90dp"

/>

3. AlignLeft: AlignLeft is used to make the left edge of the view match the left edge of the given
anchor view ID and must be a reference to another resource, in the form of Example:
android:layout_ alignLeft =”@+id/button1″.

Below is the code and layout image in which we have aligned a view with id textView2 left of
another view with id textView.

<!-- textView2 alignLeft of textView -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:id="@+id/textView2"

android:layout_alignLeft="@+id/textView"

android:text="Text2 alignLeft of Text1"

android:layout_below="@+id/textView"

MOBILE APPLICATION DEVELOPMENT 66


android:layout_marginTop="20dp"/>

4. AlignRight: AlignRight property is used to make 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 like this
example: android:layout_alignRight=”@+id/button1″

Below is the code and layout image in which we have aligned a view with id textView2 right of
another view with id textView.

<!-- textView2 alignRight of textView-->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:id="@+id/textView2"

android:layout_alignRight="@+id/textView"

android:text="Text2 alignRight of Text1"

android:layout_below="@+id/textView"

android:layout_marginTop="20dp"/>

5.AlignStart: AlignStart property is used to 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 of like this
example: android:layout_alignStart=”@+id/button1″

Below is the alignStart code and layout image in which we have aligned a view with id textView2
start of another view with id textView.

<!-- Text2 alignStart-->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

MOBILE APPLICATION DEVELOPMENT 67


android:id="@+id/textView2"

android:text="Text2 align start of Text1"

android:layout_alignStart="@+id/textView"

/>

6. AlignTop: AlignTop property is used to 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 like this
example: android:layout_alignTop=”@+id/button1″.

Below is the alignTop code and layout image in which we have aligned a view with id textView
Top of another image with id imageView.

<!--text is align top on Image-->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:id="@+id/textView"

android:layout_alignTop="@+id/imageView"

android:text="Text Here is AlignTop on Image"

/>

7. AlignParentBottom: If alignParentBottom property is true, makes the bottom edge of this


view match the bottom edge of the parent. The value of align parent bottom is either true or false.
Example: android:layout_alignParentBottom=”true”

AlignParentBottom and alignBottom are two different properties. In alignBottom we give


the reference of another view in the form of id that the view is aligned at the bottom of referenced
view but in alignParentBottom the bottom edge of the view matches the bottom edge of the
parent.

Below is the alignParentBottom code and layout image in which textView is simply displayed
using the alignParentBottom.

MOBILE APPLICATION DEVELOPMENT 68


<!-- textView is alignParentBottom -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:id="@+id/textView"

android:text="Text Here is AlignParentBottom with bottom margin of 120dp"

android:layout_alignParentBottom="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_marginBottom="120dp" />

8. AlignParentEnd: If alignParentEnd property is true, then it makes the end edge of this view
match the end edge of the parent. The value of align parent End is either true or false. Example:
android:layout_alignParentEnd=”true”.

In alignParentEnd the bottom edge of the view matches the bottom edge of the parent.
Below is the alignParentEnd code and layout image in which textView is simply displayed on
Image in the end.

<!-- Text displayed in the end of parent image-->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:id="@+id/textView"

android:text="Text in Parent End"

android:layout_alignBottom="@+id/imageView"
android:layout_alignParentEnd="true"
/>
MOBILE APPLICATION DEVELOPMENT 69
9. AlignParentLeft: If alignParentLeft property is true, makes the left edge of this view match the
left edge of the parent. The value of align parent left is either true or false. Example:
android:layout_alignParentLeft=”true”.

AlignParentLeft and alignLeft are two different properties. In alignLeft we give the
reference of another view in the form of id that the view is aligned to the left of the referenced
view but in alignParentLeft the left edge of the view matches the left edge of the parent.

Below is the alignParentLeft example code and layout image in which textView is simply
displayed on parent Image in the left side.

<!-- align parent left in Android -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:id="@+id/textView"

android:text="Text in Parent Left"

android:layout_alignBottom="@+id/imageView"

android:layout_alignParentLeft="true"

/>

MOBILE APPLICATION DEVELOPMENT 70


10. AlignParentRight: If alignParentRight property is true, then it makes the right edge of this
view match the right edge of the parent. The value of align parent right is either true or false.
Example: android:layout_alignParentRight=”true”.

Important Note: alignParentRight and alignRight are two different properties. In alignRight we
give the reference of another view in the form of id that the view is aligned to the right of the
referenced view but in alignParentRight the right edge of the view matches the right edge of the
parent.

Below is the alignParentRight example code and layout image in which textView is simply
displayed on parent Image in the right side.

<!-- alignRightParent Example -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:id="@+id/textView"

android:text="Text in Parent Right"

android:layout_alignBottom="@+id/imageView"

android:layout_alignParentRight="true"
/>

11. AlignParentStart: If alignParentStart is true, then it makes the start edge of this view match
the start edge of the parent. The value of align parent start is either true or false. Example:
android:layout_alignParentStart=”true”.

AlignParentStart and alignStart are two different properties, In alignStart we give the
reference of another view in the form of id that the view is aligned at the start of referenced view
but in alignParentStart the start edge of the view matches the start edge of the
parent(RelativeLayout).

Below is the alignParentStart example code and layout image in which textView is simply
displayed on parent Image in the right side.

MOBILE APPLICATION DEVELOPMENT 71


<!-- alignParentStart Example -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:id="@+id/textView"

android:text="Text in Parent Start"

android:layout_alignTop="@+id/imageView"

android:layout_alignParentStart="true"

/>

12. AlignParentTop: If alignParentTop is true, then it makes the top edge of this view match the
top edge of the parent. The value of align parent Top is either true or false. Example:
android:layout_alignParenTop=”true”.

AlignParentTop and alignTop are two different properties, In alignTop we give the
reference of another view in the form of id that the view is aligned to the top of the referenced
view but in alignParentTop the top edge of the view matches the top edge of the
parent(RelativeLayout).

Below is the example code of alignParentTop property and also layout image.

<!-- alignParentTop example -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Text1 align parent top"

android:layout_alignParentTop="true"

MOBILE APPLICATION DEVELOPMENT 72


android:layout_margin="20dp"

android:textSize="20sp"

android:textColor="#000"/>

13. CenterInParent: If center in parent is true, makes the view in the center of the screen
vertically and horizontally. The value of center in parent is either true or false. Example:
android:layout_centerInParent=”true”.

Below is the example code of centerInParent property and also layout image.

<!-- centerInParent example -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Text1 center in parent"

android:layout_centerInParent="true"

android:textSize="20sp"

android:textColor="#000"

/>

14. CenterHorizontal: If centerHorizontal property is true, makes the view horizontally center.
The value of centerHorizontal is either true or false.Example: android:layout_centerHorizontal
=”true”.

Below is the example code of centerHorizontal property and also layout image.

MOBILE APPLICATION DEVELOPMENT 73


<!-- centerHorizontal example -->

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 center Horizontal"
android:layout_centerHorizontal="true"
android:textSize="20sp"
android:textColor="#000"
/>

15. CenterVertical: If centerVertical property is true, make the view vertically center. The value
of align parent bottom is either true or false. Example: android:layout_centerVertical=”true”.

Below is the example code of centerVertical property and also layout image.

<!-- centerVertical example -->


<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 center vertical"
android:layout_centerVertical="true"
android:textSize="20sp"
android:textColor="#000"

/>

MOBILE APPLICATION DEVELOPMENT 74


Relative Layout Examples With Code And Explanation:

Example 1: Here we are designing a simple log in screen in Android Studio using Relative
Layout. Below is the final output:

Below is the code of activity_main.xml for designing UI with explanation included in it:

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

<!--Relative Layout Is Used-->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent">

<!--Text View for Displaying SIGN IN Text At Top of UI-->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:text="SIGN IN"

android:id="@+id/textView3"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true" />

<!--Text View for Displaying Username-->

<TextView

android:id="@+id/userName"
MOBILE APPLICATION DEVELOPMENT 75
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="@dimen/activity_horizontal_margin"

android:layout_marginTop="110dp"

android:text="UserName:"

android:textColor="#000000"

android:textSize="20sp" />

<!--Text View for Displaying Password-->

<TextView

android:id="@+id/password"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/userName"

android:layout_margin="@dimen/activity_horizontal_margin"

android:text="Password:"

android:textColor="#000000"

android:textSize="20sp" />

<!--Edit Text for Filling Username-->

<EditText

android:id="@+id/edt_userName"

android:layout_width="fill_parent"

android:layout_height="40dp"

android:layout_marginLeft="@dimen/activity_horizontal_margin"

android:layout_marginTop="100dp"

MOBILE APPLICATION DEVELOPMENT 76


android:layout_toRightOf="@+id/userName"

android:hint="User Name" />

<!--Edit Text for Filling Password-->

<EditText

android:layout_width="fill_parent"

android:layout_height="40dp"

android:layout_below="@+id/edt_userName"

android:layout_centerVertical="true"

android:layout_toRightOf="@+id/password"

android:hint="Password" />

<!--Button for Clicking after filling details-->

<Button

android:id="@+id/btnLogin"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/password"

android:layout_centerHorizontal="true"

android:layout_marginTop="20dp"

android:background="#03B424"

android:text="Login"

android:textColor="#ffffff"

android:textStyle="bold" />

</RelativeLayout>

MOBILE APPLICATION DEVELOPMENT 77


Output:

Absolute Layout:
an Absolute Layout is a layout used to design the custom layouts. In this layout you can specify
the exact location of its children by using x and y coordinates.

Absolute layout are harder to maintain for different mobile screen sizes than other types of layouts
because we set the exact location of a child view or called component. The positioning is based on
x(top) and y(left) coordinates and that positioning is not as useful in world of various screen
resolutions(sizes) and aspect ratios.
Absolute layout is depreciated in Android because of the same reason as discussed in above note.

Android Absolute Layout Syntax Code:


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<!-- add child view‟s here -->

</AbsoluteLayout>

Attributes of Absolute Layout:

1. Id: In android id is a attribute used to uniquely identify a Absolute Layout.


Below is id attribute‟s example code with explanation included.

MOBILE APPLICATION DEVELOPMENT 78


<AbsoluteLayout

android:id="@+id/absoluteLayout"

android:layout_width="fill_parent"

android:layout_height="fill_parent"/>

2. Layout_x: In Absolute Layout layout_x attribute is used to specify the x- coordinate of the
view(TextView or any other view). The possible value for this is in dp or px.

Below is the layout_x attribute‟s example code with explanation included in which we set the
200px value for the x-coordinate.

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="AbhiAndroid"

android:textSize="25sp"

android:layout_x="200px"/> <!--x-coordinates of a text view in AbsoluteLayout-->

3. Layout_y: In AbsoluteLayout layout_y attribute is used to specify the y- coordinate of the


view(TextView or any other view). The possible value for this is in dp or px.

Below is the layout_y attribute‟s example code with explanation included in which we set the
200px value for the y- coordinate.

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

MOBILE APPLICATION DEVELOPMENT 79


android:text="AbhiAndroid"

android:textSize="25sp"

android:layout_y="200px"/><!--y-coordinate of a text view in Android Studio-->

Example of Absolute Layout in Android:


Below is the example code of Absolute Layout in which we design a login screen with two field
user name and password and one button for login. We set the all views using x and y coordinates
of the screen and set the values in px(pixels). Below is the final output and code:

Step 1: Create a new project and name it Absolute Layout Example.

Select File -> New -> New Project. Fill the forms and click “Finish” button.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code. Here we
are designing a login form inside Absolute Layout.

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<TextView

android:layout_x="110px"

android:layout_y="110px"

android:text="User Name"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<EditText

MOBILE APPLICATION DEVELOPMENT 80


android:layout_x="250px"

android:layout_y="80px"

android:width="100px"

android:layout_width="200dp"

android:layout_height="wrap_content" />

<TextView

android:layout_x="110px"

android:layout_y="200px"

android:text="Password"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<EditText

android:layout_x="250px"

android:layout_y="150px"

android:width="100px"

android:layout_width="200dp"

android:layout_height="wrap_content" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Log In"

android:layout_x="300px"

android:layout_y="300px"/>

</AbsoluteLayout>

Step 3: Now Open java -> package -> MainActivity.java and paste the below code.

package example.abhiandriod.absolytelayoutexample

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

MOBILE APPLICATION DEVELOPMENT 81


import android.view.Menu;

import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item) {

// Handle action bar item clicks here. The action bar will

// automatically handle clicks on the Home/Up button, so long

// as you specify a parent activity in AndroidManifest.xml.

int id = item.getItemId();

//noinspection SimplifiableIfStatement

if (id == R.id.action_settings) {

return true;

return super.onOptionsItemSelected(item);

MOBILE APPLICATION DEVELOPMENT 82


Step 4: Now Open Manifests and click on AndroidManifest.xml and paste the below code

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="example.abhiandriod.absolytelayoutexample" >

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".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>

Step 5: Lastly Open res -> values ->strings.xml and paste the below code.

<resources>

<string name="app_name">AbsolyteLayoutExample</string>

<string name="hello_world">Hello world!</string>

<string name="action_settings">Settings</string>

</resources>

MOBILE APPLICATION DEVELOPMENT 83


Output:

Now run the App in Emulator or AVD. You will see the login form designed in Absoulte Layout
having fix x and y coordinate.

Try opening the same layout in different size Emulator and you will see it doesn‟t fit in different
size device. That‟s why Android has depreciated the use of Absolute Layout.

Using Image View:


Image View class is used to display an image file in application. Image file is easy to use
but hard to master in Android, because of the various screen sizes in Android devices. An android
is enriched with some of the best UI design widgets that allows us to build good looking and
attractive UI based application.
Important Note: ImageView comes with different configuration options to support different scale
types. Scale type options are used for scaling the bounds of an image to the bounds of the
imageview. Some of them scaleTypes configuration properties are center, center_crop, fit_xy,
fitStart etc. You can read our ScaleType tutorial to learn all details on it.
Below is an ImageView code in XML:
Make sure to save lion image in drawable folder
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion" />

MOBILE APPLICATION DEVELOPMENT 84


Attributes of ImageView:
Now let‟s we discuss some important attributes that helps us to configure a ImageView in
your xml file.
1. Id: id is an attribute used to uniquely identify a image view in android. Below is the example
code in which we set the id of a image view.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
2. Src: Src is an attribute used to set a source file or you can say image in your imageview to
make your layout attractive.
Below is the example code in which we set the source of a imageview lion which is saved in
drawable folder.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion" />
<!--set the source of an image view-->
We can also set the source image at run time programmatically in java class. For that we use
setImageResource() method as shown in below example code.
/*Add in Oncreate() funtion after setContentView()*/
ImageView simpleImageView=(ImageView) findViewById(R.id.simpleImageView);
simpleImageView.setImageResource(R.drawable.lion);//set the source in java class

3. Background: Background attribute is used to set the background of a ImageView. We can


set a color or a drawable in the background of a ImageView. Below is the example code in which
we set the black color in the background and an image in the src attribute of image view.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
android:background="#000"/>
<!--black color in background of a image view-->
MOBILE APPLICATION DEVELOPMENT 85
We can also set the background at run time programmatically in java class. In below example
code we set the black color in the background of a image view.
/*Add in Oncreate() funtion after setContentView()*/
ImageView simpleImageView=(ImageView) findViewById(R.id.simpleImageView);
simpleImageView.setBackgroundColor(Color.BLACK);//set black color in background of a
image view in java class
4. Padding: Padding attribute is used to set the padding from left, right, top or bottom of the
Imageview.
 PaddingRight: set the padding from the right side of the image view.
 PaddingLeft: set the padding from the left side of the image view.
 PaddingTop: set the padding from the top side of the image view.
 PaddingBottom: set the padding from the bottom side of the image view.
 Padding: set the padding from the all side‟s of the image view.
Below is the example code of padding attribute in which we set the 30dp padding from all the
side‟s of a image view.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000"
android:src="@drawable/lion"
android:padding="30dp"/>
<!--set 30dp padding from all the sides-->

MOBILE APPLICATION DEVELOPMENT 86


5. ScaleType: ScaleType is an attribute used to control how the image should be re-sized or
moved to match the size of this image view. The value for scale type attribute can be fit_xy,
center_crop, fitStart etc.
Below is the example code of scale type in which we set the scale type of image view to fit_xy.
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
android:scaleType="fitXY"/>
<!--set scale type fit xy-->

Let‟s we take an example of scale type to understand the actual working of scale type in a image
view.
In below example code we set the value for scale type “fitStart” which is used to fit the image in
the start of the image view as shown below:
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
android:scaleType="fitStart"/>
<!--set scale type fit start of image view-->

MOBILE APPLICATION DEVELOPMENT 87


Example of ImageView:
Below is the example of imageview in which we display two animal images of Lion and Monkey.
And whenever user click on an image Animal name is displayed as toast on screen. Below is the
final output and code:

Step 1: Create a new project and name it ImageView Example.


In this step we create a new project in android studio by filling all the necessary details of the app
like app name, package name, api versions etc.
Select File -> New -> New Project and Fill the forms and click "Finish" button.
Step 2: Download two images lion and monkey from the web. Now save those images in the
drawable folder of your project.

Step 3: Now open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we add the code for displaying an image view on the screen in a relative layout. Here
make sure you have already saved two images name lion and monkey in your drawable folder.
<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"

MOBILE APPLICATION DEVELOPMENT 88


tools:context=".MainActivity">
<ImageView
android:id="@+id/simpleImageViewLion"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="@drawable/lion" />
<ImageView
android:id="@+id/simpleImageViewMonkey"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="@+id/simpleImageViewLion"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:src="@drawable/monkey" />
</RelativeLayout>

Step 4: Now open app -> java -> package -> MainActivity.java and add the following code:
In this step we add the code to initiate the image view‟s and then perform click event on them.
package example.abhiandriod.imageviewexample;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView simpleImageViewLion = (ImageView) findViewById(R.id.simpleImageView
Lion); //get the id of first image view
ImageView simpleImageViewMonkey = (ImageView) findViewById(R.id.simpleImage
ViewMonkey);//get the id of second image view
simpleImageViewLion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Lion", Toast.LENGTH_LONG).show();
//display the text on image click event
}
});
simpleImageViewMonkey.setOnClickListener(new View.OnClickListener() {

MOBILE APPLICATION DEVELOPMENT 89


@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Monkey", Toast.LENGTH_LONG).show();
//display the text on image click event
}
});
}

}
Output:
AVD in Emulator and run the App. You will see the images of Lion and Monkey displayed on
screen. Click on any Animal image and his name will appear on Screen. We clicked on Lion.

Frame Layout:
Frame Layout is one of the simplest layout to organize view controls. They are designed to
block an area on the screen. Frame Layout should be used to hold child view, because it can be
difficult to display single views at a specific area on the screen without overlapping each other.
We can add multiple children to a Frame Layout and control their position by assigning gravity to
each child, using the android:layout_gravity attribute.

Attributes of Frame Layout:


Lets see different properties of Frame Layout which will be used while designing Android App
UI:

MOBILE APPLICATION DEVELOPMENT 90


1. android:id:
This is the unique id which identifies the layout in the R.java file.
Below is the id attribute‟s example with explanation included in which we define the id for Frame
Layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
2. android:foreground:
Foreground defines the drawable to draw over the content and this may be a color value. Possible
color values can be in the form of “#rgb”, “#argb”, “#rrggbb”, or “#aarrggbb”. This all are
different color code model used.
Example: In Below example of foreground we set the green color for foreground of frameLayout
so the ImageView and other child views of this layout will not be shown.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:foregroundGravity="fill"
android:foreground="#0f0"><!--foreground color for a FrameLayout-->
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
>
<!-- Imageview will not be shown because of foreground color which is drawn over it-->

<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"
/>
<!--Textview will not be shown because of foreground color is drawn over it-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="abhiAndroid"/>
</LinearLayout>
</FrameLayout>

MOBILE APPLICATION DEVELOPMENT 91


On applying android:foregroud feature, all the views taken in the framelayout will goes to the
background and the framelayout comes in the foreground i.e. over the views. We can set the
@drawable/image_name or the color in the foreground.
3. android:foregroundGravity:
This defines the gravity to apply to the foreground drawable. Default value of gravity is fill. We
can set values in the form of “top”, ”center_vertical” , ”fill_vertical”, ”center_horizontal”,
”fill_horizontal”, ”center”, ”fill”, ”clip_vertical”, ”clip_horizontal”, ”bottom”, ”left” or ”right” .
It is used to set the gravity of foreground. We can also set multiple values by using “|”. Ex:
fill_horizontal|top .Both the fill_horizontal and top gravity are set to framelayout.
In the above same example of foreground we also set the foregroundGravity of FrameLayout to
fill.
4. android:visibility:
This determine whether to make the view visible, invisible or gone.
visible – the view is present and also visible
invisible – The view is present but not visible
gone – The view is neither present nor visible

5. android:measureAllChildren
This determines whether to measure all children including gone state visibility or just those which
are in the visible or invisible state of measuring visibility. The default value of measureallchildren
is false. We can set values in the form of Boolean i.e. “true” OR “false”.
This may also be a reference to a resource (in the form “@[package:]type:name“) or theme
attribute (in the form “?[package:][type:]name“) containing a value of this type.
If measuresAllChildren is set true then it will show actual width and height of frame layout even if
the views visibility is in gone state.
Examples of Frame layout having measuresAllChildren attribute:
In the below code the ImageView visibility is set gone and measuresAllChildren is set true. The
output will show actual height and width the Frame Layout despite visibility is set gone. We have
used Toast to display the height and width:
MOBILE APPLICATION DEVELOPMENT 92
Below is the Code of activity_main.xml
Make sure you have image in Drawable folder. In our case we have used ic_launcher image which
we added in Drawable.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:measureAllChildren="true"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:src="@drawable/ic_launcher"/>
</FrameLayout>
Below is the code of MainActivity.java . Here we have used Toast to display height and width
on screen.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
FrameLayout frame=(FrameLayout)findViewById(R.id.frame);
frame.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int width = frame.getMeasuredWidth();
int height = frame.getMeasuredHeight();
Toast.makeText(getApplicationContext(),"width="+width+"
height="+height,Toast.LENGTH_SHORT).show();
}
}
When you run the App in Emulator you will see the below output:

MOBILE APPLICATION DEVELOPMENT 93


Explanation of Example: It measures all the children in the layout. For ex: If we setVisiblity
of an view be gone and set measuresAllChildren property to be true, then also it will also count to
that view which is not visible, but if we set the measuresAllChildren property to be false, then it
will not count to that view which is gone.

Example of Frame Layout in Android Studio:


Example 1: Frame Layout using layout gravity. Here we will put textview at different position
in Frame Layout. Below is the code and final output:

Step 1: Create a new project in Android Studio and name it FrameTesting. (Select File -> New -
> New Project. Fill the forms and click “Finish” button)
Step 2: Now Open res -> layout -> activity_main.xml and add the following code. Here we are
putting different TextView in Frame Layout.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<TextView android:text="LeftTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightTop"
android:layout_gravity="top|right" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CentreTop"
android:layout_gravity="top|center_horizontal" />
<TextView android:text="Left"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"

MOBILE APPLICATION DEVELOPMENT 94


android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Right"
android:layout_gravity="right|center_vertical" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Centre"
android:layout_gravity="center" />
<TextView android:text="LeftBottom"
android:layout_gravity="left|bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightBottom"
android:layout_gravity="right|bottom" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CenterBottom"
android:layout_gravity="center|bottom" />
</FrameLayout>
Step 3: Let the MainActivity.java has default Android code or add the below code:
package abhiandroid.com.frametesting;
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);
}
}
Output:
Run the App in Emulator, you will see Textview positioned at various position in FrameLayout

MOBILE APPLICATION DEVELOPMENT 95


Example 2: Example of A Frame Layout without using layout gravity. Here we will use a
image to fill complete screen and then we will write “abhiandroid” text in center of the image. We
will do all this inside Frame Layout. Below is the code and final output:

Step 1: Create a new project and name it FrameWithoutGravity.


Select File -> New -> New Project in Android Studio. Fill the forms and click “Finish” button.
Step 2: Now open res -> layout -> activity_main.xml and add following code. Here we are
designing ImageView and TextView inside Frame Layout.
Make sure you have an image saved in drawable folder name img_name. If you have saved other
image with different name then please change it in the code.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/img_name" /><!--Change image as per your name of image saved
in drawable-->
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="abhiAndroid"
android:textSize="30sp"
android:textColor="#f3f3f3"
android:textStyle="bold" />
</FrameLayout>
Step 3: Let the MainActivity.java has default java code or add the below code:
package abhiandroid.com.framewithoutgravity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {

MOBILE APPLICATION DEVELOPMENT 96


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Output:
Now run the App in Emulator and you will see the below output of Frame layout without Gravity:

Example 3 (BONUS): Another Example Of Creating A Frame Layout programmatically( i.e.


Using Java Class only). Here we will create the same output as above but we won‟t use xml.
Instead we will use JAVA class.

Step 1: Create a new project in Android Studio. In our case we created FrameLayoutJAVA.
Step 2: Just add the following code to your MainActivity.java . Explanation is included in the
code as comments.
package abhiandroid.com.farmelayoutjava;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

MOBILE APPLICATION DEVELOPMENT 97


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.img_name);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
TextView textView1 = new TextView(this);
textView1.setText("abhiAndroid");
textView1.setTextSize(30);
textView1.setGravity(Gravity.CENTER);
textView1.setTextColor(Color.parseColor("#f3f3f3"));
textView1.setTypeface(null, Typeface.BOLD);
textView1.setLayoutParams(new
FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
FrameLayout.LayoutParams lp1 = new FrameLayout.LayoutParams(FrameLayout.
LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
lp1.setMargins(0,20,0,0);
textView1.setLayoutParams(lp1);

//Initializing frame layout

FrameLayout framelayout = new FrameLayout(this);


framelayout.setLayoutParams(new
AbsListView.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
//Adding views to FrameLayout
framelayout.addView(imageView);
framelayout.addView(textView1);
setContentView(framelayout);
}
}
Output:

MOBILE APPLICATION DEVELOPMENT 98


Table Layout:
Table Layout is used to arrange the group of views into rows and columns. Table
Layout containers do not display a border line for their columns, rows or cells. A Table will have
as many columns as the row with the most cells.

Row and Column in Table Layout Android


A table can also leave the cells empty but cells can‟t span the columns as they can
in HTML(Hypertext markup language).
Table Layout In Android:
 For building a row in a table we will use the <TableRow> element. Table row objects are
the child views of a table layout.
 Each row of the table has zero or more cells and each cell can hold only one view object
like ImageView, TextView or any other view.
 Total width of a table is defined by its parent container
 Column can be both stretchable and shrinkable. If shrinkable then the width of column can
be shrunk to fit the table into its parent object and if stretchable then it can expand in width
to fit any extra space available.
We cannot specify the width of the children‟s of the Table layout. Here, width always matches
parent width. However, the height attribute can be defined by a child; default value of height
attribute is wrapping content.
Basic Table Layout code in XML:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:collapseColumns="0"> <!-- collapse the first column of the table row-->
<!-- first row of the table layout-->
<TableRow
android:id="@+id/row1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Add elements/columns in the first row-->
</TableRow>
</TableLayout>

MOBILE APPLICATION DEVELOPMENT 99


Attributes of TableLayout in Android:
Now let‟s we discuss some important attributes that help us to configure a table layout
in XML file (layout).
1. Id: id attribute is used to uniquely identify a Table Layout.
<TableLayout
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent/>
2. Stretch Columns: Stretch column attribute is used in Table Layout to change the default width
of a column which is set equal to the width of the widest column but we can also stretch the
columns to take up available free space by using this attribute. The value that assigned to this
attribute can be a single column number or a comma delimited list of column numbers (1, 2,
3…n).
If the value is 1 then the second column is stretched to take up any available space in the row,
because of the column numbers are started from 0.
If the value is 0,1 then both the first and second columns of table are stretched to take up the
available space in the row. If the value is „*‟ then all the columns are stretched to take up the
available space.
Below is the example code of stretch column attribute of table layout with explanation included in
which we stretch the first column of layout.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/simpleTableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1"> <!-- stretch the second column of the layout-->
<!-- first row of the table layout-->
<TableRow
android:id="@+id/firstRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- first element of the row-->
<TextView
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Text 1"
android:textColor="#000"
android:textSize="12dp" />
<TextView
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
MOBILE APPLICATION DEVELOPMENT 100
android:padding="18dip"
android:text="Text 2"
android:textColor="#000"
android:textSize="14dp" />
</TableRow>
</TableLayout>

3. Shrink Columns: Shrink column attribute is used to shrink or reduce the width of the
column„s. We can specify either a single column or a comma delimited list of column numbers for
this attribute. The content in the specified columns word-wraps to reduce their width. If the value
is 0 then the first column‟s width shrinks or reduces by word wrapping its content. If the value is
0,1 then both first and second columns are shrinks or reduced by word wrapping its content. If the
value is „*‟ then the content of all columns is word wrapped to shrink their widths.
Below is the example code of shrink column attribute of table layout with explanation included in
which we shrink the first column of layout.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="0"> <!-- shrink the first column of the layout-->
<!-- first row of the table layout-->
<TableRow
android:id="@+id/firstRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- first element of the first row-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Shrink Column Example"
android:textColor="#000"
android:textSize="18dp" />
</TableRow>
</TableLayout>

MOBILE APPLICATION DEVELOPMENT 101


4. Collapse Columns: Collapse columns attribute is used to collapse or invisible the column‟s
of a table layout. These columns are the part of the table information but are invisible.
If the values is 0 then the first column appears collapsed, i.e it is the part of table but it is invisible.
Below is the example code of collapse columns with explanation included in which we collapse
the first column of table means first column is an part of table but it is invisible so you can see
only the second column in screenshot.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:collapseColumns="0"> <!-- collapse the first column of the table row-->
<!-- first row of the table layout-->
<TableRow
android:id="@+id/simpleTableLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- first element of the row that is the part of table but it is invisible-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Columns 1"
android:textColor="#000"
android:textSize="18dp" />
<!-- second element of the row that is shown in the screenshot-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Columns 2"
android:textColor="#000"
android:textSize="18dp" />
</TableRow>
</TableLayout>

MOBILE APPLICATION DEVELOPMENT 102


Example In Android Studio:
Below is an example of Table layout in Android where we display a login form with two fields
user name and password and one login button and whenever a user click on that button a message
will be displayed by using a Toast.
Below you can download project code, see final output and step by step explanation of the
example:

Step 1: Create a new project and name it TableLayoutExample


Step 2: Open res -> layout ->activity_main.xml (or) main.xml and add following code:
In this step we open an xml file ( activity_main.xml ) and add the code for displaying username
and password fields by using textview and edittext with one login button.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:orientation="vertical"
android:stretchColumns="1">
<TableRow android:padding="5dip">
<TextView
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:layout_span="2"
android:gravity="center_horizontal"
android:text="@string/loginForm"
android:textColor="#0ff"
android:textSize="25sp"
android:textStyle="bold" />
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_column="0"

MOBILE APPLICATION DEVELOPMENT 103


android:layout_marginLeft="10dp"
android:text="@string/userName"
android:textColor="#fff"
android:textSize="16sp" />
<EditText
android:id="@+id/userName"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="10dp"
android:background="#fff"
android:hint="@string/userName"
android:padding="5dp"
android:textColor="#000" />
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:text="@string/password"
android:textColor="#fff"
android:textSize="16sp" />
<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:background="#fff"
android:hint="@string/password"
android:padding="5dp"
android:textColor="#000" />
</TableRow>
<TableRow android:layout_marginTop="20dp">
<Button
android:id="@+id/loginBtn"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_span="2"
android:background="#0ff"
android:text="@string/login"
android:textColor="#000"
android:textSize="20sp"
android:textStyle="bold" />
</TableRow>

MOBILE APPLICATION DEVELOPMENT 104


</TableLayout>
Step 3: Open src -> package -> MainActivity.java
In this step we open MainActivity and add the code to initiate the edittext and button and then
perform click event on button and display the message by using a Toast.
package example.abhiandriod.tablelayoutexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate a button
Button loginButton = (Button) findViewById(R.id.loginBtn);
// perform click event on the button
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hello AbhiAndroid..!!!",
Toast.LENGTH_LONG).show(); // display a toast message
}
});
}
}
Step 4: Open res -> values -> strings.xml
In this step we open string file which is used to store string data of the app.
<resources>
<string name="app_name">TableLayoutExample</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="loginForm">Login Form</string>
<string name="userName">UserName</string>
<string name="password">Password</string>
<string name="login">LogIn</string>
</resources>
Output:
Now run the App and you will see the Login form UI which we designed in Table Layout.

MOBILE APPLICATION DEVELOPMENT 105


Grid Layout:
Grid Layout lays out views in a two-dimensional grid pattern, that is, in a series of rows and
columns. The intersection of row and column is known as a grid cell, and it is the place where
child views are placed. It is easier to use Grid Layout when compared to Table Layout. Without
specifying intermediate views, we can flexibly place the views randomly in the grid by specifying
their row and column positions. More than one view can be placed in a grid cell. Besides this,
views can span multiple grid cells too.
Note
No need to specify layout_height and layout_width for the GridLayout child views as they default
to WRAP_CONTENT.
Specifying Row and Column Position:
The two attributes that are used to specify the row and column position of the grid cell for
inserting views are
android:layout_row and android:layout_column.
Together, they specify the exact location of the grid cell for placing the view. For example, the
following statements place the view at the first row and column position of the grid:
android:layout_row="0"
android:layout_column="0"
When either or both of the preceding attributes are not specified, GridLayout uses the next grid
cell by default for placing the view.
Spanning Rows and Columns:
Views can span rows or columns if desired. The attributes used for doing so
are android:layout_rowSpan and android:layout_columnSpan. For example, the following
statement spans the view to two rows:
android:layout_rowSpan="2"
Similarly, the following statement spans the view to three columns:
android:layout_columnSpan="3"
Inserting Spaces in the GridLayout:
For inserting spaces, a spacing view called Space is used. That is, to insert spaces, the Space view
is inserted as a child view. For example, the following statements insert a space at the second row
in the GridLayout. The width and height of the blank space are 50dp and 10dp:
<Space
android:layout_row="1"
android:layout_column="0"
android:layout_width="50dp"
android:layout_height="10dp" />
Similarly, the following statements insert a space at the third row in the GridLayout that spans
three columns:
<Space
android:layout_row="3"
android:layout_column="0"
android:layout_columnSpan="3"
android:layout_gravity="fill" />
Let‟s apply the knowledge gained so far in arranging controls in a GridLayout. The application
has controls arranged in the same way as we saw in TableLayout . but in GridLayout instead. So,

MOBILE APPLICATION DEVELOPMENT 106


let‟s create a new Android project called GridLayoutLayoutApp. Make its layout
file, activity_grid_layout_app.xml.
Listing 3.14. The Layout File activity_grid_layout_app.xml on Arranging Controls in a
GridLayout Container
<GridLayout 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="horizontal"
android:rowCount="7"
android:columnCount="2" >
<TextView
android:layout_row="0"
android:layout_column="0"
android:text="New Product Form"
android:typeface="serif"
android:layout_columnSpan="2"
android:layout_gravity="center_horizontal"
android:textSize="20dip" />
<Space
android:layout_row="1"
android:layout_column="0"
android:layout_width="50dp"
android:layout_height="10dp" />
<TextView
android:layout_row="2"
android:layout_column="0"
android:text="Product Code:" />
<EditText
android:id="@+id/prod_code"
android:layout_width="100dip" />
<TextView
android:text="Product Name:" />
<EditText
android:layout_row="3"
android:layout_column="1"
android:id="@+id/prod_name"
android:layout_width="200dip" />
<TextView
android:layout_row="4"
android:layout_column="0"
android:text="Product Price:" />
<EditText
android:layout_row="4"
android:layout_column="1"
android:id="@+id/prod_price"

MOBILE APPLICATION DEVELOPMENT 107


android:layout_width="100dip" />
<Space
android:layout_row="5"
android:layout_column="0"
android:layout_width="50dp"
android:layout_height="20dp" />
<Button
android:layout_row="6"
android:layout_column="0"
android:id="@+id/add_button"
android:text="Add Product" />
<Button
android:id="@+id/cancel_button"
android:text="Cancel" />
</GridLayout>
In the preceding code, the GridLayout is defined as consisting of seven rows and two columns.
The orientation of GridLayout is set to horizontal; that is, controls are placed in rows. It means
that while specifying the grid location of a view, if we don‟t specify the column number, the next
available column is assigned to it. As said earlier, the layout_width and layout_height attributes
are not specified for any of the views laid in GridLayout because the default value wrap_content is
considered for them. Remember, the row and column numbers are zero-based.
A TextView with the text New Product Form is set to appear at the first row and column position
of the grid. The text appears in serif font and in 20dip size. The text spans two columns and
appears at the center of the row.
• A blank space is inserted at the second row and first column position. The width and height of
the blank space are 50dp and 10dp, respectively.
• A TextView with the text Product Code: is set to appear at the third row and first column
position of the grid.
• An EditText control with the ID prod_code of width 100dip is set to appear at the third row and
second column position of the grid, that is, to the right of the text Product Code:. The question is
even though we didn‟t specify row and column position for the EditText control, how it will
appear at the third row and second column position? The answer is because the orientation of
the GridLayoutis horizontal, the current row (if it is not full) and the next column (if available) are
considered the default location for the control to be inserted.
• A TextView with the text Product Name: is set to appear at the fourth row and first column
position of the grid. Because both columns of the third row are full, the fourth row is considered
the location for this view.
• An EditText control with the ID prod_name of width 200dip is set to appear at the fourth row
and second column of the grid, that is, to the right of the text Product Name:.
• A TextView with the text Product Price: is set to appear at the fifth row and first column of the
grid.
• An EditText control with the ID prod_price of width 100dip is set to appear at the fifth row and
second column position of the grid, that is, to the right of the text Product Price:.
• A blank space is inserted at the sixth row and first column position. The width and height of the
blank space are 50dp and 20dp, respectively.

MOBILE APPLICATION DEVELOPMENT 108


• A Button control with the caption "Add Product" is set to appear at the seventh row and first
column of the grid.
• A Button control with the caption "Cancel" is set to appear at the seventh row and second
column of the grid.
There is no need to write any code in the Java activity file GridLayoutAppActivity.java. When the
application is run, the controls are laid out in the grid pattern.

Figure 3.15. Controls organized in the GridLayout

Adapting to Screen Orientation:


As with almost all smartphones, Android supports two screen orientations: portrait and landscape.
When the screen orientation of an Android device is changed, the current activity being displayed
is destroyed and re-created automatically to redraw its content in the new orientation. In other
words, the onCreate() method of the activity is fired whenever there is a change in screen
orientation.
Portrait mode is longer in height and smaller in width, whereas landscape mode is wider but
smaller in height. Being wider, landscape mode has more empty space on the right side of the
screen. At the same time, some of the controls don‟t appear because of the smaller height. Thus,
controls need to be laid out differently in the two screen orientations because of the difference in
the height and width of the two orientations.
There are two ways to handle changes in screen orientation:
• Anchoring controls—Set the controls to appear at the places relative to the four edges of the
screen. When the screen orientation changes, the controls do not disappear but are rearranged
relative to the four edges.
• Defining layout for each mode—A new layout file is defined for each of the two screen
orientations. One has the controls arranged to suit the Portrait mode, and the other has the controls
arranged to suit the Landscape mode.
Anchoring Controls:
For anchoring controls relative to the four edges of the screen, we use a RelativeLayout container.
Let‟s examine this method by creating an Android project called ScreenOrientationApp.

MOBILE APPLICATION DEVELOPMENT 109


To lay out the controls at locations relative to the four edges of the screen, write the code in the
layout file activity_screen_orientation_app.xml.
Listing 3.15. The Layout file activity_screen_orientation_app.xml on Laying Out Controls
Relative to the Four Edges of the Screen
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:layout_marginLeft="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="28dip"
android:layout_toRightOf="@id/Apple"
android:layout_marginLeft="15dip"
android:layout_marginRight="10dip"
android:layout_alignParentTop="true" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="200dip"
android:layout_height="50dip"
android:layout_marginTop="15dip"
android:layout_below="@id/Apple"
android:layout_alignParentLeft="true" />
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:minWidth="100dp"
android:layout_alignParentRight="true"
android:layout_below="@id/Banana" />
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="100dip"
android:layout_height="wrap_content"

MOBILE APPLICATION DEVELOPMENT 110


android:layout_below="@id/Banana"
android:paddingTop="15dip"
android:paddingLeft="25dip"
android:paddingRight="25dip" />
</RelativeLayout>
Shows five Button controls arranged in a RelativeLayout container. The controls are aligned
relative to the edges of the container or in relation to each other. Let‟s keep the activity
file ScreenOrientationAppActivity.java unchanged with the default code.
Listing 3.16. Default Code in the Java Activity File ScreenOrientationAppActivity.java
package com.androidunleashed.screenorientationapp;

import android.app.Activity;
import android.os.Bundle;

public class ScreenOrientationAppActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_orientation_app);
}
}
When the application is run while in the default portrait mode. Because the five Button controls
are placed in relation to the four edges of the container and in relation to each other, none of
the Button controls disappear if the screen is rotated to landscape mode. To switch
between portrait mode and landscape mode on the device emulator, press the Ctrl+F11 keys.

Figure 3.16. (left) Controls in portrait mode, and (right) the controls in landscapemode

Defining Layout for Each Mode:


In this method, we define two layouts. One arranges the controls in the default portrait mode, and
the other arranges the controls in landscape mode. For laying out the controls for portrait mode in
the default layout file activity_screen_orientation_app.xml (found in the res/layout folder).
MOBILE APPLICATION DEVELOPMENT 111
Listing 3.17. The Layout File activity_screen_orientation_app.xml on Laying Out Controls
in portrait Mode
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
</LinearLayout>
we can see that five Button controls are vertically arranged in a LinearLayout container, one
below the other. This vertical arrangement makes a few of the Button controls disappear when the
screen is in landscape mode.

MOBILE APPLICATION DEVELOPMENT 112


If we run the application without defining the layout for the landscape mode, we find the controls
arranged in portrait mode. But when we switch the screen orientation to landscape, we find the
last two Button controls have disappeared. This is because in landscape mode, the screen becomes
wider but shorter in height.

Figure 3.17. (left) Controls in portrait mode, and (right) some controls disappear
in landscape mode.
To use the blank space on the right side of the screen in landscape mode, we need to define
another layout file, activity_screen_orientation_app.xml, created in the res/layout-land folder.
The layout-land folder has to be created manually inside the res folder. Right-click on
the resfolder in the Package Explorer window and select the New, Folder option. A dialog box
opens, asking for the name for the new folder. Assign the name layout-land to the new folder, and
click the Finish button. Copy the activity_screen_orientation_app.xml file from
the res/layoutfolder and paste it into res/layout-land folder. Modify
the activity_screen_orientation_app.xml file in the res/layout-land folder so as to arrange the
controls in landscape mode.
Listing 3.18. The Layout File activity_screen_orientation_app.xml in the res/layout-
landFolder
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"

MOBILE APPLICATION DEVELOPMENT 113


android:layout_width="250dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_toRightOf="@id/Apple" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_below="@id/Apple" />
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_below="@id/Apple"
android:layout_toRightOf="@id/Banana" />
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_below="@id/Banana" />
</RelativeLayout>
In this code block, we can see that, to fill up the blank space on the right side of the screen,
the Mangoand Grapes button controls are set to appear to the right of the apple and banana button
controls.
We can also detect the screen orientation via Java code. Let‟s modify the activity
file ScreenOrientationAppActivity.java to display a toast message when the screen switches
between landscape mode and portrait mode. The code written in the Java activity file Screen
OrientationappActivity.java.
Listing 3.19. Code Written in the Java Activity File ScreenOrientationappActivity.java
package com.androidunleashed.screenorientationapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class ScreenOrientationAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {

MOBILE APPLICATION DEVELOPMENT 114


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_orientation_app);
if(getResources().getDisplayMetrics().widthPixels>getResources().getDisplayMetrics().
heightPixels)
{
Toast.makeText(this,"Screen switched to Landscape mode",Toast.LENGTH_SHORT).
show();
}
else
{
Toast.makeText(this,"Screen switched to Portrait mode",Toast.LENGTH_SHORT).
show();
}
}
}
Now, when we run the application, the controls appear in portrait mode and in landscape mode.
We can see that none of the Button controls are now hidden in landscape mode.

Figure 3.18. (left) Controls in portrait mode, and (right) all controls are visible
in landscape mode.

Utilizing Resources and Media:


Resources include text data, bitmaps, audio, videos, and other items used by the Android
application. Most commonly resources are kept separately in XML files and accessed in Java code
through the IDs assigned to them. In this chapter you learn to access media too, that is, access and
use images, audio, and video in Android applications.
Resources:
Resources in Android refer to the external files that hold the information, such as strings, images,
layouts, and audio, to be supplied to an Android application. Because resources are external, we
can maintain and modify them whenever we want without disturbing the code. For example, the
strings resource keeps the strings used in an Android application. Changing the string content in
the resource file is easier when compared to applying changes to hard-coded strings that are

MOBILE APPLICATION DEVELOPMENT 115


scattered in the application code. Also, by creating several resource files, each supporting different
hardware, we can make our applications applicable to diverse hardware systems. For example, we
can have several layouts for screen size and orientation and use them dynamically when we want.
Resources are broadly divided into three categories—values, drawable, and layout—and are
stored in the res folder of our project hierarchy. The values resources in turn represent resources
such as strings, colors, dimensions, styles, and string or integer arrays. All resource types have a
respective subfolder in the res folder. The ADT Wizard automatically creates a res folder that
contains subfolders for the values, drawable, and layout resources.

The res folder showing the nested drawable (drawable-hdpi, drawable-ldpi, drawable-mdpi)
layouts and values folders and their content
Types of Resources:
A brief outline of the three folders is provided here:
• drawable folder—Depending on the target platform chosen, our application can have either a
single directory, drawable, or four directories, drawable-ldpi, drawable-mdpi, drawable-hdpi,
and drawable-xhdpi, where we can store the images used in our application. If our application has
a single directory, drawable, then the images to be used in our application, regardless of
resolution, are stored in it. If our application has four directories, then the images with different
screen resolutions are stored in the respective directories. That is, the images of low, medium,
high, and extra high resolutions are stored in the drawable-ldpi, drawable-mdpi, drawable-hdpi,
and drawable-xhdpi directories, respectively. Android chooses the image(s) from the respective
directory, depending on the density of the device used to run the application.
• layout folder—This folder contains a layout file automatically created for us. The default name
assigned to this file is activity_main.xml, but we can assign any name to it. We saw how to use
this file to lay out Views in the desired format.
• menu folder—This folder contains XML file(s) that represent application menus. Again, the
default name assigned to the menu file that is automatically created for us is activity_main.xml,
but we can change the name if we want.
• values folder—This folder by default contains a strings.xml file that we can use to define values
resources that include strings, colors, dimensions, styles, and string or integer arrays. We can also
create individual XML files for each of these resources instead. The folder also contains

MOBILE APPLICATION DEVELOPMENT 116


the styles.xml file that declares the standard platform‟s default light theme. The following is a list
of some XML files that we can create in the values folder:
• arrays.xml—For defining arrays resources
• colors.xml—For defining color resources that define color values
• dimens.xml—For defining dimension resources to standardize certain application measurements
• strings.xml—For defining string resources
• styles.xml—For defining styles resources to format or change the appearance of our views and
application
There are many Android devices with different Android versions, and managing themes across
them is a critical task. To manage themes for different Android versions, different values folders
in the /resfolder containing individual themes are maintained. The idea is that on the basis of the
platform version, the desired theme will be automatically selected from the respective folder.
• values-v11—The folder contains the styles.xml file that declares the holographic theme, which
is used when the application runs on Android 3.0 (API Level 11) or higher. That is, if the API
level of the device is 11 or higher, the styles.xml file present in this folder overrides
the styles.xml file present in the res/values folder.
• values-v14—The folder contains the styles.xml file that declares the DeviceDefault theme,
which is used when the application runs on Android 4.0 (API Level 14) or higher.
Besides these default subdirectories automatically created by ADT, there are several
subdirectories that we can manually create in the res folder to categorize and keep our resources
tidy.
Supported Subdirectories of the res Folder:

When our application is built, all resources are compiled and included in our application package.
On compilation, an R class file is created that contains references to all the resources created and
hence enables us to reference them in the Java code. For each of the resource types, the R
class contains static subclasses for string, drawable, and layout resource types. The subclasses
created are R.string, R.drawable, and R.layout, respectively. Through these subclasses, we can
access their associated resources in Java code.

Creating Values Resources:


The resources in the values directory include different types, such as strings, colors, dimensions,
and string or integer arrays. All the values are stored in XML files in the res/values folder. It is
preferred to have a separate XML file for each type of resource in the valuesdirectory. The
filename can be anything, but most commonly, the string resources file is named strings.xml.
MOBILE APPLICATION DEVELOPMENT 117
Remember, the resource filenames should contain only lowercase letters, numbers, period (.), and
underscore (_) symbols.
We can have any number of XML files to represent resources, provided they reside in
the /res/values subdirectory. Never save resource files directly inside the res/ folder—it will cause
a compiler error.
Default Code in the strings.xml File:
<resources>
<string name="app_name">ValuesResourcesApp</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_values_resources_app">ValuesResourcesAppActivity</string>
</resources>
The two string resources with the name attributes hello and app_name are assigned to
the TextView (in main.xml) and label attribute of the Activity tag (in AndroidManifest.xml) to
display the name of the activity and the application name, respectively, while running the project.
Code Written in the strings.xml File:
<resources>
<string name="app_name">ValuesResourcesApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_values_resources_app">ValuesResourcesAppActivity</string>
<string name="str_name">XYZ Restaurant</string>
<string name="str_address">11, Hill View Street, New York</string>
<string name="str_message"><b>Welcome</b></string>
</resources>
We can see that the string resources file has a root element, <resources>, followed by one or more
child elements, <string>. Each <string> element represents one string resource. Besides the text
for the string resource, it contains a name property used to assign a unique resource ID to the
string. That is, the names assigned to the four string resources, app_name, str_name, str_address,
and str_message, are the resource IDs of the respective strings, and we can use these resource IDs
in other resource files or the Java code for accessing the respective string resources.
We can use the string resources of the preceding XML file in other resource files by using the
following syntax:
@string/resource_ID
For example, to access the string resource with the resource ID str_address in another resource
file, we use the following code:
@string/str_address
All the string resources mentioned in the preceding string resource file will be compiled and
placed in the R.java file. In the Java code, we can access the resources from the R.java file, using
the following syntax:
R.string.resource_ID
In preceding syntax, the string refers to the resource type; that is, every resource ID needs to be
prefixed by the resource type. Likewise, to access the drawable and layout resources, we prefix
the resource ID by R.drawable and R.layout, respectively. There is no need to add any prefix
while accessing any control from the layout. The resource ID is enough. The syntax is

MOBILE APPLICATION DEVELOPMENT 118


R.id.resource_ID
Hence, to access the string resource with the resource ID str_address in the Java code, we use the
following statement:
R.string.str_name
We use the getString() method and pass the resource ID of the concerned string resource to access
it in Java code. Hence, the complete command to access the string resource with the resource
ID str_address is getString(R.string.str_address);
We can also use HTML tags <b>, <i>, and <u> to make a string appear bold, italicized, or
underlined. To access the string resources defined in the file strings.xml and to apply them to
the TextView controls, the layout
file activity_values_resources_app.xml
Code Written in the Layout File activity_values_resources_app.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message" />
</LinearLayout>
In this code block, the statement android:text="@string/str_name" accesses a string resource from
a resource file res/values/strings.xml, whose name property is str_name. The text in the string
resource str_name is assigned to the TextView for display.
Similarly, the string resource str_message is accessed and assigned to the TextView
message_view.
Hence, the text XYZ Restaurant and the Welcome message appear on the screen through the first
and third TextViewcontrols, name_view and message_view, respectively. But the
middle TextView, address_view, does not display any text, as it is not assigned any string
resource.
Code Written in the Java Activity File ValuesResourcesAppActivity.java:
package com.androidunleashed.valuesresourcesapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ValuesResourcesAppActivity extends Activity {

MOBILE APPLICATION DEVELOPMENT 119


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_values_resources_app);
String strAddress=getString(R.string.str_address);
TextView addressView=(TextView)findViewById(R.id.address_view);
addressView.setText(strAddress);
}
}
The string resource with the resource ID str_address is accessed and assigned to the String
object strAddress. The TextView with the ID addressView is accessed from the layout and is
mapped to the TextView object addressView. The content of the string resource that is saved in
the strAddress object is assigned to the TextView to display. That is, the content of the string
resource str_address is assigned to a TextView so it will be displayed on the screen.

The three TextViews displaying the text assigned to them via String resource and Java code
Let‟s change the size of the text in these TextView controls via dimension resources.
Dimension Resources:
Dimension resources are used for standardizing certain application measurements. These
resources can be used to specify the sizes for fonts, layouts, and widgets. Also, we can modify the
size of any control in the application without changing the code. Besides this, we can define
dimensions for different screen resolutions and densities to support different hardware.
To try out dimension resources, let‟s open the application ValuesResourcesApp and add an XML
file called dimens.xml to the values folder.
Code Written in the dimens.xml File:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="small_size">15dp</dimen>
<dimen name="medium_size">15sp</dimen>
<dimen name="large_size">20pt</dimen>
</resources>
We can see that the dimension resource is defined throughthe dimen element.
The dimen element contains a numerical value followed by unit of measurement.
Like other resources, it includes the nameproperty to specify the ID of the resource.
We can use any of the following units of measurement:
• px—Pixels
• in—Inches
• mm—Millimeters
• pt—Points
MOBILE APPLICATION DEVELOPMENT 120
• dp—Density-independent pixels based on a 160-dpi (pixel density per inch) screen
• sp—Scale-independent pixels
In the strings.xml file, we have defined three dimension resources: 15dp, 15sp, and 20pt,
represented by the three resource IDs small_size, medium_size, and large_size, respectively. Let‟s
apply the dimension resources to our TextView controls name_view, address_view,
and message_view. First, we learn to apply dimension resources through the layout file followed
by Java code. To apply dimension resources to the TextView controls,
modify activity_values_resources_app.xml.
The Layout File activity_values_resources_app.xml on Applying Dimension Resources
to TextView Controls
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"
android:textSize="@dimen/small_size" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message"
android:textSize="@dimen/large_size" />
</LinearLayout>
In the preceding code block, the two statements access the two dimension
resources small_size and large_size and apply to the two TextViewswith the IDs name_view and
message_view, respectively.
Their text size is set to 15px and 20sp, respectively. Now let‟s see how to apply dimension
resources to a View via Java code.
android:textSize="@dimen/small_size"
and
android:textSize="@dimen/large_size"
To apply the dimension resource medium_size to our TextView address_view, add these
statements to the Java file ValuesResourcesAppActivity.java:
float addressSize= this.getResources().getDimension(R.dimen.medium_size);
addressView.setTextSize(addressSize);
The TextView to which we want to apply the dimension resource is accessed from the layout file
and mapped to the TextView object addressView. Thereafter, we access our Resources object by
calling there the get Resource() method on our activity object.

MOBILE APPLICATION DEVELOPMENT 121


Then, through the Resources object, we access the dimension by supplying its resource ID to
the getDimension() method. The dimension accessed is then applied to the TextView using
the setTextSize() method. After the application is run, we find that the three TextView controls
appear in the sizes defined in the dimension resources.

Different dimensions applied to the three TextViews via dimension resources


Let‟s now see how to apply colors to our Views via color resources.
Color Resources:
To define a color resource, we use the color element.
The color value is specified in the form of hexadecimal RGB values preceded by an
optional Alpha channel.
The Alpha channel represents the transparency. We can specify the color either through single-
character hex values or double-character hex values formats, as shown here:
• #RGB—For example, #F00 for a Red color.
• #RRGGBB—For example, #FF0000 for a Red color
• #ARGB—For example, #5F00 for a Red color with an Alpha of 5.
• #AARRGGBB—For example, #50FF0000 for a Red color with an Alpha of 50.
To apply color resources to our application ValuesResourcesApp, let‟s add an XML file
called colors.xml to the values folder. In the colors.xml file, define a few color resources by
writing the following lines of code in it:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red_color">#F00</color>
<color name="green_color">#00FF00</color>
<color name="blue_alpha_color">#500000FF</color>
</resources>
This code block defines three color resources that represent the three colors red, green,
and blue (bit transparent) through the resource IDs red_color, green_color, and blue_alpha_color,
respectively. Again, we learn to apply color resources to our Views with two methods: via the
layout file and Java code. To apply color resources via the layout
file activity_values_resources_app.xml.
The Layout File activity_values_resources_app.xml on Applying Color Resources
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_view"

MOBILE APPLICATION DEVELOPMENT 122


android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"
android:textSize="@dimen/small_size"
android:textColor="@color/red_color"/>
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message"
android:textSize="@dimen/large_size"
android:textColor="@color/blue_alpha_color"/>
</LinearLayout>
In the preceding code block, the two statements
android:textColor="@color/red_color"
and
android:textColor="@color/blue_alpha_color"
access the color resources with the IDs red_color and blueAlpha_color, from the resource file and
assign them to the text of the two TextViews, name_view and message_view. This changes their
color to red and blue, respectively.
To apply the color resource to the TextView address_view, we use Java code. Add the following
lines of code to the Java file ValuesResourcesAppActivity.java to access the color resource and
apply it to the desired View:
int addressColor=this.getResources().getColor(R.color.green_color);
addressView.setTextColor(addressColor);
Here, the Resources object is accessed by calling the getResources() method. The Resources
object, the getColor() method, is called to access the color resource by supplying its resource ID.
The color accessed is then applied to the addressView TextView by using
the setTextColor() method.
The Code Written in the Java Activity File ValuesResourcesAppActivity.java
package com.androidunleashed.valuesresourcesapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ValuesResourcesAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_values_resources_app);
String strAddress=getString(R.string.str_address);
TextView addressView=(TextView)findViewById(R.id.address_view);
addressView.setText(strAddress);

MOBILE APPLICATION DEVELOPMENT 123


float addressSize= this.getResources().getDimension(R.dimen.medium_size);
addressView.setTextSize(addressSize);
int addressColor=this.getResources().getColor(R.color.green_color);
addressView.setTextColor(addressColor);
}
}
When the application is run, we see the three TextView controls appearing in the colors defined in
the color resources. Because the print book is in black and white, the TextViewcontrols are
distinguished through different sizes.

The three TextViews displayed in different colors applied via the Color Resource.
The TextView controls are distinguished through different sizes.
Styles and Themes:
A style is a collection of attributes such as color, font, margin, and padding that we can apply
collectively to our Views, Activity, or an entire application. That is, instead of applying attributes
individually to the components of our application, we can create a style incorporating all these
attributes and quickly apply it instead. Through styles, we can apply a consistent dynamic look to
our Views, Activity, and to the overall application. Also, we can easily change the appearance of
our Views and application by simply specifying a different style or modifying the properties of the
existing style, all without disturbing the Java code.
A style is created by using a style element with one or more item child elements.
The style element includes a name property to specify the resource ID. Each item element
includes a name property to define the attributes such as color, font, and so on. An item element
defines an attribute and its value shown in this syntax:
<resources>
<style name="resource_ID">
<item name="attribute_name">value </item>
</style>
</resources>
Styles support inheritance; that is, the attributes of any existing style can be accessed and included
in the current style by using the parent property of the style element. For example, the attributes
defined in a style named style1 can be included in the style named style2 by making use of
the parent property in style2 as shown here:
<style name="style2" parent="style1" >
To apply styles to the individual Views in the layout file, open the styles.xml file that already
exists in the values folder. In the styles.xml file, define the styles.

MOBILE APPLICATION DEVELOPMENT 124


The Code Written in the styles.xml File:
<resources>
<style name="AppTheme" parent="android:Theme.Light" />
<style name="style1">
<item name="android:textColor">#00FF00 </item>
<item name="android:typeface">serif</item>
<item name="android:textSize">30sp </item>
</style>
<style name="style2" parent="style1" >
<item name="android:textColor">#0000FF</item>
<item name="android:typeface">sans</item>
<item name="android:background">#FF0000</item>
<item name="android:padding">10dip</item>
</style>
<style name="style3" parent="style2" >
<item name="android:textColor">#00FF00</item>
<item name="android:background">#00000000</item>
<item name="android:typeface">monospace</item>
<item name="android:gravity">center</item>
</style>
</resources>
We can see that three styles are defined with IDs: style1, style2, and style3, respectively.
The style1 defines three attributes that
• Set the text color to green
• Set the font (typeface) to serif
• Set the font size to 30sp
The style2 inherits style1; hence it automatically gets the preceding three attributes.
The style2overrides the font and text color, changing them to sans and blue, respectively.
Also, style2includes the attributes to set the background color of the text to red and the text
spacing to 10dipfrom all four sides of the container. Thus, it also means that style 2 now has the
attributes that
• Set the font size to 30sp (inherited from style1)
• Set the text color to blue
• Set the font (typeface) to sans
• Set the text background color to red
• Set the padding (text spacing from all four sides of the container) to 10dip
The style3 inherits style2, which means it receives all these attributes. It overrides certain
attributes redefining the text color, background color, and the font to green, black,
and monospace, respectively. Also, style3 includes the gravity attribute set to center that makes
the content of a View appear at the center. Hence, the style3 has the following attributes that
• Set the font size to 30sp
• Set the text color to green
• Set the background color of the text to black
• Set the font (typeface) to monospace
• Set the padding (text spacing from all four sides of the container) to 10dip
• Make the content appear at the center of the View

MOBILE APPLICATION DEVELOPMENT 125


The Layout File activity_values_resources_app.xml on Applying Styles to TextView Control
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name_view"
style="@style/style1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"/>
<TextView
android:id="@+id/address_view"
style="@style/style2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_address" />
<TextView
android:id="@+id/message_view"
style="@style/style3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message" />
</LinearLayout>
We can see that style1, style2, and style3 are applied to the three TextView controls name_view,
address_view, and message_view, respectively. Hence, the content of the first TextView appears
in green, serif font and 30sp in size. Similarly, the content of the second TextView appears in a
blue foreground color, red background color, sans font, 30sp in size, and the spacing (padding)
between the text and the TextView on all four sides is 10dip. The content in the
third TextView appears in monospace font, green foreground color, black background color,
size 30sp in and the text appears at the center of the TextView.
The padding attribute value will be overridden by the gravity attribute, making the text appear at
the center of the TextView.
Code in the Java Activity File ValuesResourcesAppActivity.java
package com.androidunleashed.valuesresourcesapp;
import android.app.Activity;
import android.os.Bundle;
public class ValuesResourcesAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_values_resources_app);
}
}
When the application is run, we get the output.

MOBILE APPLICATION DEVELOPMENT 126


The three TextViews with different styles applied to them Applying Themes
We can apply the style element to an entire Activity or application by adding the android:theme
attribute to the Android manifest. For example, after we add the android:theme attribute to
the <activity> element in the Android manifest, all the attributes of the style are applied to
every View within the Activity. Similarly, after we add the android:theme attribute to
the <application> element in the Android manifest, all the attributes of the style are applied to all
the activities in the application.
Default Code in the AndroidManifest.xml File
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.valuesresourcesapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".ValuesResourcesAppActivity"
android:label="@string/title_activity_values_resources_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>
</manifest>
Code in the AndroidManifest.xml File on Modifying the android:theme Attribute
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.valuesresourcesapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk

MOBILE APPLICATION DEVELOPMENT 127


android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/style3" >
<activity
android:name=".ValuesResourcesAppActivity"
android:label="@string/title_activity_values_resources_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
To see the impact of applying the style to the entire application, we need to remove the styles in
the layout file that were applied to the individual TextView controls.
The Layout file activity_values_resources_app.xml on Removing Styles
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_address" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message" />
</LinearLayout>
After the application is run, we find that the content of all three Views appears
in monospace font, green foreground color, black background color, 30sp in size, and the text
appears at the center of the container.

MOBILE APPLICATION DEVELOPMENT 128


The three TextViews styled by the application of a theme

Using Drawable Resources:


When it comes to displaying images, Android supports three common image formats: PNG, JPG,
and GIF. The images for the Android application are stored in the directory res/drawable.
Depending on the target platform chosen while creating a new application, ADT either creates a
single directory, res/drawable, or several: drawable-ldpi, drawable-mdpi, drawable-hdpi,
and drawable-xhdpi. Each directory is meant for storing images of different screen resolutions. To
support devices of different densities, we can store the images of low, medium, high, and extra
high resolutions in the drawable-ldpi, drawable-mdpi, drawable-hdpi, and drawable-
xhdpi directories, respectively. The images with resolutions of 320dpi, 240dpi, 160dpi,
and 120dpi and sizes 96x96px, 72x72px, 48x48px, and 36x36px are usually stored in
the res/drawable-xhdpi, res/drawable-hdpi, res/drawable-mdpi, and res/drawable-ldpi folders,
respectively. At runtime, depending on the density of the device on which the application is run,
Android automatically chooses the correct resolution image. For example, if the application is
running on a high-density device and the requested drawable resource is available in the drawable-
hdpi folder, Android uses it in the application. If Android doesn‟t find the image in the drawable-
hdpi folder, it searches for the image in other directories to find the closest match. Displaying
images is easy. We just put our image in the res/drawable folders and then refer to it in the code.
In this section, we learn to display images in an Android application.
Let‟s create a new Android project called DispImageApp. As we said earlier, to display an image
in an application, the file needs to be added to the res/drawable folder. Android supports images
of almost all formats, but it prefers to use the PNG format. Copy a few images, for
example, bintupic.png of 96x96px, 72x72px, 48x48px, and 36x36px in size and resolutions
of 320dpi, 240dpi, 160dpi, and 120dpi, respectively, into the res/drawable-xhdpi, res/drawable-
hdpi, res/drawable-mdpi, and res/drawable-ldpi folders, respectively. Remember, all image
filenames should be lowercase and contain only letters, numbers, and underscores. After we add
images to the res/drawable folders, the gen folder is regenerated where the R.java file resides.
The R.java file includes a reference to the newly added image and hence can be used in the layout
file or other Java code. The syntax for referencing the image in the layout file is
@drawable/image_filename
The image_filename in the syntax shown refers to the base name of the file, that is, the filename
without the extension. For example, the image file, bintupic.png, that we just added to
the res/drawable folder is accessed as @drawable/bintupic in the layout file and other resources

MOBILE APPLICATION DEVELOPMENT 129


and as R.drawable.bintupic in the Java code. The extension of the image file, .png is never used
when referencing it.
To display the image, let‟s add an ImageView control to the layout file.
The Layout File activity_disp_image_app.xml on Adding the ImageView Control
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/bintupic"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
We can see that an ImageView control is defined with the ID image_toview. To make our image
display through an ImageView control, we reference it via its src attribute. That is, we use the
following statement to assign or refer the image in the res/drawable folder:
android:src="@drawable/bintupic"
This statement loads the image bintupic.png, which we pasted into the res/drawable folder. We
don‟t need to write any Java code for displaying the image. After the application is run, the image
is displayed.

The image displayed through an ImageView control using a drawable resource


We can also specify the image for the ImageView control through Java code. To try this, let‟s
remove the reference to the bintupic image in the ImageView control that we made through
the srcattribute:
android:src="@drawable/bintupic"
After we remove the image reference from the ImageView control, the layout
file, activity_disp_image_app.xml.
The Layout file activity_disp_image_app.xml on Removing the Image Reference from
the ImageView Control
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
MOBILE APPLICATION DEVELOPMENT 130
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_toview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
If we run the application now, nothing appears on the screen, as no image has been referenced by
the ImageView control.
The Java Activity File DispImageAppActivity.java
package com.androidunleashed.dispimageapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class DispImageAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disp_image_app);
ImageView image = (ImageView) findViewById(R.id.image_toview);
image.setImageResource(R.drawable.bintupic);
}
}
In the preceding Java file, the statement ImageView image = (ImageView) findViewById
(R.id.image_toview);
gets the ImageView control from the layout file and stores it in an ImageView object
called image.That is, the image is an ImageView object that now refers to the ImageView control
placed in the layout file. Via the setImageResource() method used in this statement
image.setImage Resource(R.drawable.bintupic);
The image bintupic.png stored in the res/drawable folder is assigned to the ImageView control for
display.
We have now learned that the setImageResource() method can be used to change the image of
the ImageView control dynamically at runtime. Let‟s use this method to modify our application so
that it switches images when a button is clicked. When the button is clicked again, the previous
image is redisplayed in the ImageView control. The button that is most suitable for this type of
application is a ToggleButton, which flips between two states.

Switching States with Toggle Buttons:


Android Toggle Button is used to display on and off state on a button. Switch is another type of
toggle button that‟s predominantly used since Android 4.0. Android Switch provides a slider
control. Both ToggleButton and Switch are subclasses of CompoundButton class.
XML Attributes used to define a ToggleButton are described below.
1. android:disabledAlpha: The alpha to apply to the indicator when disabled
2. android:textOff: The text for the button when it is not checked
3. android:textOn: The text for the button when it is checked.

MOBILE APPLICATION DEVELOPMENT 131


To modify the ToggleButton programmatically the following methods are used.
1. CharSequence getTextOff(): It returns the text when button is not in the checked state
2. CharSequence getTextOn(): It returns the text for when button is in the checked state
3. void setChecked(boolean checked): It changes the checked state of this button
Android Switch:
Android Switch or SwitchCompat widget ( a part of AppCompat library which provides
backward compatibility for lower Android versions upto Android API v7) is a custom On-Off
slider which is commonly seen in phone settings.
Advantages of Android Switch Widget:
1. It is the best replacement for checkboxes and RadioButtons
2. Implementation takes only less than a minute
3. No need to use much drawables and other resources
The xml layout of a SwitchCompat is given below:
<android.support.v7.widget.SwitchCompat
android:id="@+id/switchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Switch example"
/>
android:text is used to display a Text besides the slider switch button.
Example:
The state of the Toggle Buttons would be displayed in a SnackBar when
the FloatingActionButton is pressed. The state of the Switch button is changed to true whenever
the action button of the snackbar is clicked. Or the state is displayed in the snackbar by sliding the
switch.
Android Toggle Button and Switch Project Structure:

MOBILE APPLICATION DEVELOPMENT 132


Android Toggle Button Code:
The activity_main.xml remains the same. The content_main.xml contains two Toggle Buttons and
a Switch checked to false by default as shown in the code snippet below :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.journaldev.switchandtoggle.MainActivity"
tools:showIn="@layout/activity_main">

<ToggleButton
android:id="@+id/tb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="ToggleButton 1"
android:textOff="Off"
android:textOn="On" />
<ToggleButton
android:id="@+id/tb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tb1"
android:layout_alignBottom="@+id/tb1"
android:layout_toRightOf="@+id/tb1"
android:text="ToggleButton 2"
android:textOff="Off"
android:textOn="On" />
<android.support.v7.widget.SwitchCompat
android:id="@+id/switchButton"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:checked="false"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Switch example"/>
</RelativeLayout>

MOBILE APPLICATION DEVELOPMENT 133


The MainActivity.java is given below:
package com.journaldev.switchandtoggle;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
ToggleButton tb1, tb2;
SwitchCompat switchCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
StringBuilder result = new StringBuilder();
result.append("ToggleButton1 : ").append(tb1.getText());
result.append("\nToggleButton2 : ").append(tb2.getText());
Snackbar snackbar= Snackbar.make(view, result.toString(), Snackbar.LENGTH_LONG)
.setAction("SWITCH ENABLE", new View.OnClickListener() {
@Override
public void onClick(View v) {
switchCompat.setChecked(true);
}
});
snackbar.setActionTextColor(Color.RED);
snackbar.show();
}
});
tb1= (ToggleButton)findViewById(R.id.tb1);
tb2=(ToggleButton)findViewById(R.id.tb2);
switchCompat=(SwitchCompat)findViewById(R.id.switchButton);
switchCompat.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {

MOBILE APPLICATION DEVELOPMENT 134


@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Snackbar.make(buttonView, "Switch state checked "+isChecked, Snackbar.LENGTH_LONG)
.setAction("ACTION",null).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.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
A String builder is used to get the current state of the toggle buttons and append them to display in
the snackbar.
Switch button being a subclass of Compound Button, an OnCheckChangeListener is
implemented.

MOBILE APPLICATION DEVELOPMENT 135


Creating an Images Switcher Application:
ImageSwitcher is a specialized ViewSwitcher that contain ImageView type children. It is an
element of transition widget which helps us to add transitions on the images. It is mainly useful to
animate an image on screen. ImageSwitcher switches smoothly between two images and thus
provides a way of transitioning from one Image to another through appropriate animations.

Basic ImageSwitcher code in XML:


<ImageSwitcher
android:id="@+id/simpleImageSwitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

Steps for Implementation of ImageSwitcher:


1. Get the reference of ImageSwitcher in class using findViewById() method, or you can also
create an object dynamically.
2. Set a factory using switcherid.setFactory()
3. Set an in-animation using switcherid.setInAnimation()
4. Set an out-animation using switcherid.setOutAnimation()

Important Methods Of ImageSwitcher:


Let‟s we discuss some important methods of ImageSwitcher that may be called in order to manage
the ImageSwitcher.
1. setFactory(ViewFactory factory): This method is used to create a new view for
ImageSwitcher. By using this method we create a new ImageView and replace the old view with
that.
Below code create a new view using setFactory method.
ImageSwitcher simpleImageSwitcher=(ImageSwitcher)findViewById(R.id.simpleImage
Switcher); // get reference of ImageSwitcher
// Set the ViewFactory of the ImageSwitcher that will create ImageView object when asked
imageSwitcher.setFactory (new ViewSwitcher.ViewFactory () {
public View makeView() {
// TODO Auto-generated method stub
// Create a new ImageView and set it's properties
ImageView imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

MOBILE APPLICATION DEVELOPMENT 136


imageView.setLayoutParams(new
ImageSwitcher.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
return imageView;
}
});
2. SetImageDrawable (Drawable drawable): This method is used to set an image
in ImageSwitcher. In this we pass an image for Drawable.
Below we set image in ImageSwitcher by using setImageDrawable method.
ImageSwitcher simpleImageSwitcher=(ImageSwitcher)findViewById(R.id.
simpleImageSwitcher); // initiate a ImageSwitcher
simpleImageSwitcher.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
// set drawable image in ImageSwitcher

3. setImageResource(int resid): This method is also used to set an image in image switcher. The
image is passed in the form of integer id.
Below we set image in ImageSwitcher by using setImageDrawable method.
ImageSwitcher simpleImageSwitcher=(ImageSwitcher)findViewById(R.id.
simpleImageSwitcher); // initiate a ImageSwitcher
simpleImageSwitcher.setImageResource(R.drawable.ic_launcher); // set image resource in
ImageSwitcher
4. setImageURI(Uri uri): This method is also used to set an image in image switcher. The image
is passed in the form of URI.
Below we set Image in ImageSwitcher from raw folder using Uri:
Before using below code first create a raw name folder in res directory and save an image name
image1 in that folder.
ImageSwitcher simpleImageSwitcher=(ImageSwitcher)findViewById(R.id. simpleImage
Switcher); // get reference of ImageSwitcher
simpleImageSwitcher.setImageURI(Uri.parse("android.resource://" + getPackageName() + "/" +
R.raw.image1)); // set Image in ImageSwitcher from raw folder using Uri
5. loadAnimation(Context context, int id): This method is used whenever we need to define an
object of Animation class through AnimationUtils class by calling a static method loadAnimation.
Below we create an object of Animation class and load an animation by using AnimationUtils
class.
// load an animation by using AnimationUtils class
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

MOBILE APPLICATION DEVELOPMENT 137


6. setInAnimation(Animation inAnimation): This method is used to set the animation of the
appearance of the object on the screen.
Below we create an object of Animation class and load an animation by using AnimationUtils
class and then set the Animation on ImageSwitcher.
ImageSwitcher simpleImageSwitcher=(ImageSwitcher)findViewById(R.id. simpleImage
Switcher); // initiate a ImageSwitcher
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
// load an animation
simpleImageSwitcher.setInAnimation(in); // set in Animation for ImageSwitcher

7. setOutAnimation(Animation outAnimation): This method does the opposite of


setInAnimation().
Whenever we use set a new Image in ImageView, it first removes the old view using an animation
set with the setOutAnimation() method, and then places the new one using the animation set by
the setInAnimation() method.
Below we create an object of Animation class and load an animation by using AnimationUtils
class and then set the out Animation on ImageSwitcher
ImageSwitcher simpleImageSwitcher=(ImageSwitcher)findViewById(R.id. simpleImage
Switcher); // get reference of ImageSwitcher
Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right); // load an
animation
simpleImageSwitcher.setOutAnimation(out); // set out Animation for ImageSwitcher

MOBILE APPLICATION DEVELOPMENT 138


Attributes of ImageSwitcher:
Now let‟s we discuss some common attributes of a ImageSwitcher that helps us to configure it in
our layout (xml).
1. Id: id attribute is used to uniquely identify a ImageSwitcher.
Below we set the id of the ImageSwitcher that is used to uniquely identify it.
<ImageSwitcher
android:id="@+id/simpleImageSwitcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> <!-- id of ImageSwitcher that is used to uniquely
identify it -->
2. Padding: This attribute is used to set the padding from left, right, top or bottom side of a
ImageSwitcher.
 paddingRight: This attribute is used to set the padding from the right side of a
ImageSwitcher.
 paddingLeft: This attribute is used to set the padding from the left side of a
ImageSwitcher.
 paddingTop: This attribute is used to set the padding from the top side of a
ImageSwitcher.
 paddingBottom: This attribute is used to set the padding from the bottom side of a
ImageSwitcher.
 Padding: This attribute is used to set the padding from the all the side‟s of a
ImageSwitcher.
Below we set the 10dp padding from all the sides of a ImageSwitcher
<ImageSwitcher
android:id="@+id/imageSwitcher"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center_horizontal"
android:padding="10dp" /> <!-- set 10 dp padding from all the sides of TextSwitcher -->
3. Background: This attribute is used to set the background of a ImageSwitcher. We can set a
color or a drawable in the background of a ImageSwitcher.
Below is the example code with explanation included in which we set the black color for the
background of a ImageSwitcher.
<ImageSwitcher
android:id="@+id/imageSwitcher"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center_horizontal"
android:background="#000" /> <!-- set black color in the background of TextSwitcher -->

MOBILE APPLICATION DEVELOPMENT 139


Setting background In ImageSwitcher In Java class:
ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher); // get the
reference of ImageSwitcher.
imageSwitcher.setBackgroundColor(Color.BLACK); // set black color in the background of
ImageSwitcher.

ImageSwitcher Example in Android Studio:


Below is the example of ImageSwitcher in Android Studio where we display a ImageSwitcher by
using its different attributes. In this we use one Button for changing the image in ImageSwitcher.
Firstly we create an array of id‟s Images and create dynamic ImageView using setFactory method
and then load and set slide in left and slide in right animation and finally set the Image in the
ImageSwitcher on Button click using setImageResource method. Whenever a user click on next
button ImageSwitcher switch between the images and the current Image will go out and next
Image will come in with specified animation.
Below you can download complete project code, see final output and step by step explanation:

Step 1: Create a new project and name it ImageSwitcherExample


Step 2: Open res -> layout ->activity_main.xml (or) main.xml and add following code :
In this step we open an xml file and add the code for displaying a Button and a ImageSwitcher by
using its different attributes.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ImageSwitcher
android:id="@+id/simpleImageSwitcher"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp" />

<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
MOBILE APPLICATION DEVELOPMENT 140
android:layout_gravity="center"
android:background="#050"
android:textColor="#fff"
android:textStyle="bold"
android:text="NEXT" />

</LinearLayout>
Step 3: Open src -> package -> MainActivity.java
In this step we open MainActivity and add the code for initiate the ImageSwitcher and Button. In
this Firstly we create an array of id‟s Images and create dynamic ImageView using setFactory
method and then load and set slide in left and slide in right animation and finally set the Image in
the ImageSwitcher on button click using setImageResource method. Whenever a user click on
next button ImageSwitcher switch between the images and the current Image will go OUT and
next Image will come in with specified animation.
package com.example.ip_d.imageswitcherexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ViewSwitcher;

public class MainActivity extends AppCompatActivity {


private ImageSwitcher simpleImageSwitcher;
Button btnNext;

// Array of Image IDs to Show In ImageSwitcher


int imageIds[] = {R.drawable.image1, R.drawable.images2, R.drawable.image3,
R.drawable.images4, R.drawable.images5};
int count = imageIds.length;
// to keep current Index of ImageID array
int currentIndex = -1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// get The references of Button and ImageSwitcher


btnNext = (Button) findViewById(R.id.buttonNext);

MOBILE APPLICATION DEVELOPMENT 141


simpleImageSwitcher = (ImageSwitcher) findViewById(R.id.simpleImageSwitcher);
// Set the ViewFactory of the ImageSwitcher that will create ImageView object when asked
simpleImageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

public View makeView() {


// TODO Auto-generated method stub

// Create a new ImageView and set it's properties


ImageView imageView = new ImageView(getApplicationContext());
// set Scale type of ImageView to Fit Center
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
// set the Height And Width of ImageView To FIll PARENT
imageView.setLayoutParams(new
ImageSwitcher.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
return imageView;
}
});

// Declare in and out animations and load them using AnimationUtils class
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

// set the animation type to ImageSwitcher


simpleImageSwitcher.setInAnimation(in);
simpleImageSwitcher.setOutAnimation(out);

// ClickListener for NEXT button


// When clicked on Button ImageSwitcher will switch between Images
// The current Image will go OUT and next Image will come in with specified animation
btnNext.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {


// TODO Auto-generated method stub
currentIndex++;
// Check If index reaches maximum then reset it
if (currentIndex == count)
currentIndex = 0;
simpleImageSwitcher.setImageResource(imageIds[currentIndex]); // set the image in
ImageSwitcher
}
});

MOBILE APPLICATION DEVELOPMENT 142

You might also like