You are on page 1of 37

Unit-III

UNIT-III
Building Blocks for Android Application Design

Introduction to Layout:
Under Standing the Components of a Screen

Android application is an activity. An activity displays the user interface of your


application, which may contain widgets like buttons, labels, text boxes, and so on.
1. 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.
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:

Attribute Description

layout_width Specifies the width of the View or ViewGroup


layout_height Specifies the height of the View or ViewGroup
layout_marginTop Specifies extra space on the top side of the View or ViewGroup
layout_marginBottom Specifies extra space on the bottom side of the View orViewGroup
layout_marginLeft Specifies extra space on the left side of the View or ViewGroup
layout_marginRight Specifies extra space on the right side of the View or ViewGroup
layout_gravity Specifi es how child Views are positioned
layout_weight Specifi es how much of the extra space in the layout should be
allocatedto the View
layout_x Specifi es the x-coordinate of the View or ViewGroup
layout_y Specifi es the y-coordinate of the View or ViewGroup

Orientation: The orientation attribute used to set the childs/views horizontally or vertically. In


Linear layout default orientation is vertical.

C.B.I.T-C.S.E Page 1
Unit-III

Types Of Linear Layout Orientation


There are two types of linear layout orientation:
Vertical
Horizontal
As the name specified these two orientations are used to arrange their 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.

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

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:background="#e6cf00" />
C.B.I.T-C.S.E Page 2
Unit-III

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

Output Screen:

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.

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"

C.B.I.T-C.S.E Page 3
Unit-III

android:layout_height="match_parent"
android:weightSum="5"
android:orientation="horizontal">

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

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
C.B.I.T-C.S.E Page 4
Unit-III

android:text="Button 4"
android:background="#e100d5"
android:layout_weight="1"/>
</LinearLayout>

Output Screen:

II-RelativeLayout

The RelativeLayout enables you to specify how child views are positioned relative to
each other. android:id=”@+id/btnSaveA RelativeLayout is a very powerful utility for designing
a user interface because it can eliminate nested view groups and keep your layout hierarchy flat,
which improves performance. If you find yourself using several nested LinearLayout groups, you
may be able to replace them with a single RelativeLayout.

Consider the following main.xml file:

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


<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
>

C.B.I.T-C.S.E Page 5
Unit-III

<TextView
android:id=”@+id/lblComments”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Comments”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”
/>
<EditText
android:id=”@+id/txtComments”
android:layout_width=”fill_parent”
android:layout_height=”170px”
android:textSize=”18sp”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true”
/>
<Button
android:layout_width=”125px”
android:layout_height=”wrap_content”
android:text=”Save”
android:layout_below=”@+id/txtComments”
android:layout_alignRight=”@+id/txtComments”
/>
<Button
android:id=”@+id/btnCancel”
android:layout_width=”124px”
android:layout_height=”wrap_content”
android:text=”Cancel”
android:layout_below=”@+id/txtComments”
android:layout_alignLeft=”@+id/txtComments”
/>
</RelativeLayout>

Notice that each view embedded within the RelativeLayout has attributes that enable it to align
with another view. These attributes are as follows:

Positioning Views Attributes

➤➤ layout_alignParentTop
C.B.I.T-C.S.E Page 6
Unit-III

➤➤ layout_alignParentLeft
➤➤ layout_alignLeft
➤➤ layout_alignRight
➤➤ layout_below
➤➤ layout_centerHorizontal

The value for each of these attributes is the ID for the view that you are referencing. The
preceding XML UI creates the screen shown in Figure 3-9.

Some of the many layout properties available to views in a RelativeLayout include:

android:layout_alignParentTop:If "true", makes the top edge of this view match the top edge of the
parent.
android:layout_centerVertical: If "true", centers this child vertically within its parent.

android:layout_below: Positions the top edge of this view below the view specified with a resource ID.

android:layout_toRightOf :Positions the left edge of this view to the right of the view specified with a
resource ID.

These are just a few examples. All layout attributes are documented
at RelativeLayout.LayoutParams. The value for each layout property is either a boolean to enable a
layout position relative to the parent RelativeLayout or an ID that references another view in the
layout against which the view should be positioned.

III-Absolute Layout
In Android, 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. Or
AbsoluteLayout enables you to specify the exact location of its children. An Absolute Layout

C.B.I.T-C.S.E Page 7
Unit-III

lets you specify exact locations (x/y coordinates) of its children. Absolute layouts are less
flexible and harder to maintain than other types of layouts without absolute positioning.

AbsoluteLayout Attributes

Following are the important attributes specific to AbsoluteLayout



Sr.No Attribute & Description

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

2 android:layout_x
This specifies the x-coordinate of the view.

3 android:layout_y
This specifies the y-coordinate of the view.

src/com.example.demo/MainActivity.java. 

package com.example.demo;
import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

C.B.I.T-C.S.E Page 8
Unit-III

res/layout/activity_main.xmlfile –

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="OK"
android:layout_x="50px"
android:layout_y="361px" />
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_x="225px"
android:layout_y="361px" /></AbsoluteLayout>

IV-ImageView
In Android, ImageView 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.

C.B.I.T-C.S.E Page 9
Unit-III

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

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

In Java:
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()*/


C.B.I.T-C.S.E Page 10
Unit-III

ImageView simpleImageView=(ImageView) findViewById(R.id.simpleImageView);


simpleImageView.setImageResource(R.drawable.lion);//set the source 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.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<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"
C.B.I.T-C.S.E Page 11
Unit-III

android:src="@drawable/monkey" />

</RelativeLayout>

V-Frame Layout:
The FrameLayout is a placeholder on screen that you can use to display a single view.
Views that you add to a FrameLayout are always anchored to the top left of the layout. Consider
the following content in main.xml:

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


<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
>
<TextView
android:id=”@+id/lblComments”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”This is my lovely dog, Ookii”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”
/>
<FrameLayout

C.B.I.T-C.S.E Page 12
Unit-III

android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true”
>
<ImageView
android:src = “@drawable/ookii”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
/>
</FrameLayout>
</RelativeLayout>

Here, you have a FrameLayout within a RelativeLayout. Within the FrameLayout, you embed an
ImageView.

If you add another view (such as a Button view) within the FrameLayout, the view will overlap
the previous view
<?xml version=”1.0” encoding=”utf-8”?>
<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
>
<TextView
android:id=”@+id/lblComments”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”This is my lovely dog, Ookii”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”/>
<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true”
>
<ImageView
C.B.I.T-C.S.E Page 13
Unit-III

android:src = “@drawable/ookii”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
/>
<Button
android:layout_width=”124dp”
android:layout_height=”wrap_content”
android:text=”Print Picture”
/>
</FrameLayout>
</RelativeLayout>

Fig: Overlap

VI-Table Layout
In Android, 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.

C.B.I.T-C.S.E Page 14
Unit-III

Important Points About 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.

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

Following are the important attributes specific to TableLayout –

Sr.No Attribute & Description

C.B.I.T-C.S.E Page 15
Unit-III

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

2 android:collapseColumns
This specifies the zero-based index of the columns to collapse.
The column indices must be separated by a comma: 1, 2, 5.

3 android:shrinkColumns
The zero-based index of the columns to shrink. The column
indices must be separated by a comma: 1, 2, 5.

4 android:stretchColumns
The zero-based index of the columns to stretch. The column
indices must be separated by a comma: 1, 2, 5.

TableLayout 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.
C.B.I.T-C.S.E Page 16
Unit-III

<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"
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>
C.B.I.T-C.S.E Page 17
Unit-III

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

VII-Grid View :

C.B.I.T-C.S.E Page 18
Unit-III

Android GridView shows items in two-dimensional scrolling grid (rows & columns) and


the grid items are not necessarily predetermined but they automatically inserted to the layout
using a ListAdapter

An adapter actually bridges between UI components and the data source that fill data into
UI Component. Adapter can be used to supply the data to like spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterViewand they can be populated by
binding them to an Adapter, which retrieves data from an external source and creates a View that
represents each data entry.

GridView Attributes

Following are the important attributes specific to GridView −

Sr.N Attribute & Description


o

C.B.I.T-C.S.E Page 19
Unit-III

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

android:columnWidth
2 This specifies the fixed width for each column. This could be in
px, dp, sp, in, or mm.

android:gravity
3 Specifies the gravity within each cell. Possible values are top,
bottom, left, right, center, center_vertical, center_horizontal etc.

android:horizontalSpacing
4 Defines the default horizontal spacing between columns. This
could be in px, dp, sp, in, or mm.

android:numColumns
Defines how many columns to show. May be an integer value,
5
such as "100" or auto_fit which means display as many columns as
possible to fill the available space.

android:stretchMode
Defines how columns should stretch to fill the available empty
space, if any. This must be either of the values −
none − Stretching is disabled.
6
spacingWidth − The spacing between each column is stretched.
columnWidth − Each column is stretched equally.
spacingWidthUniform − The spacing between each column is
uniformly stretched..

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

VIII-Adapting to display orientation


 One of the key features of modern smartphones is their ability to switch screen
orientation, and
 Android is no exception. Android supports two screen orientations: portrait and
landscape. By default,

C.B.I.T-C.S.E Page 20
Unit-III

 when you change the display orientation of your Android device, the current activity that
is displayed
 will automatically redraw its content in the new orientation. This is because the
onCreate() event of
 the activity is fi red whenever there is a change in display orientation.
 However, when the views are redrawn, they may be drawn in their original locations
(depending on
 the layout selected). Figure 3-13 shows one of the examples illustrated earlier displayed
in both portrait
 and landscape mode.
 As you can observe in landscape mode, a lot of empty space on the right of the screen
could be used.
 Furthermore, any additional views at the bottom of the screen would be hidden when the
screen orientation is set to landscape.

In general, you can employ two techniques to handle changes in screen orientation:

➤➤ Anchoring — The easiest way is to “anchor” your views to the four edges of the screen.
When the screen orientation changes, the views can anchor neatly to the edges.
➤➤ Resizing and repositioning — Whereas anchoring and centralizing are simple techniques to
ensure that views can handle changes in screen orientation, the ultimate technique is resizing
each and every view according to the current screen orientation.
Anchoring Views

Anchoring could be easily achieved by using RelativeLayout. Consider the following main.xml
containing five Button views embedded within the <RelativeLayout> element:

C.B.I.T-C.S.E Page 21
Unit-III

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


<RelativeLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”
>
<Button
android:id=”@+id/button1”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”Top Left Button”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true”
/> <Button
android:id=”@+id/button2”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”Top Right Button”
android:layout_alignParentTop=”true”
android:layout_alignParentRight=”true”
/>
<Button
android:id=”@+id/button3”
android:layout_width=” match_parent”
android:layout_height=”wrap_content”
android:text=”Bottom Left Button”
android:layout_alignParentLeft=”true”
android:layout_alignParentBottom=”true”
/>
<Button
android:id=”@+id/button4”
android:layout_width=” match_parent”
android:layout_height=”wrap_content”
android:text=”Bottom Right Button”
android:layout_alignParentRight=”true”
android:layout_alignParentBottom=”true”
/>
<Button
android:id=”@+id/button5”
android:layout_width=” match_parent”
android:layout_height=”wrap_content”
C.B.I.T-C.S.E Page 22
Unit-III

android:text=”Middle Button”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true”
/>
</RelativeLayout

Observe the following attributes found in the various Button views:

➤➤ layout_alignParentLeft — Aligns the view to the left of the parent view


➤➤ layout_alignParentRight — Aligns the view to the right of the parent view
➤➤ layout_alignParentTop — Aligns the view to the top of the parent view
➤➤ layout_alignParentBottom — Aligns the view to the bottom of the parent view
➤➤ layout_centerVertical — Centers the view vertically within its parent view
➤➤ layout_centerHorizontal — Centers the view horizontally within its parent view

Ma naging Changes to Screen Orientation


Now that you have looked at how to implement the two techniques for adapting to screen
orientation changes, let’s explore what happens to an activity’s state when the device changes
orientation.

Resources folder:
 The res folder is used to store the values for the resources that are used in
many Android projects.
 This folder consist of files like colros.xml, strings.xml, styles.xml,dimens.xml
Colors.xml:
The colors.xml is an XML file which is used to store the colors for the resources.
Ex: <resources>

C.B.I.T-C.S.E Page 23
Unit-III

    <color name="colorPrimary">#1294c8</color>
    <color name="colorPrimaryDark">#1294c8</color>
    </resources>
Strings.xml:
 strings.xml is to define the strings in one file so that it is easy to use same string in
different positions in the android project plus it makes the project looks less messy.
 We can also define an array in this file as well.
Ex: <resources>
    <string name="app_name">Workshop app</string>
      <string name="navigation_drawer_open">Open navigation drawer</string>
    </resources>
dimens.xml:
 The dimens.xml is used for defining the dimensions for different widgets to be included
in the Android project.
Ex:
<resources>
    <dimen name=“Large">16dp</dimen>
    <dimen name=“Medium">12dp</dimen>
    <dimen name=“Small”>8dp</dimen>
</resources>
styles.xml: 
styles.xml where all the themes of the Android project are defined.
Ex:
<resources>
<style name=“style1”>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

Arrays:
 Arrays refer to collection of Values or elements.
 Arrays can be in the form of Strings or integers and are used for storing the data of their
respective data type.
 To define string arrays we need to follow the below syntax:
<string-array name=”array_name”>
<item>item1</item>

C.B.I.T-C.S.E Page 24
Unit-III

<item>item2</item>
</string-array>
 Similarly if you want to create integer array:
<integer-array name=”array_name”>
<item>item1</item>
<item>item2</item>
</integer-array>

Using Drawable Resources:


 If you want to display images on android application you need to store those images in
drawable folder.
 drawable folder available at res/drawable folder.
 For adding images to the drawable folder. Copy the image then select drawable folder
and give right click and select option paste.
 For using those images you need use @drawable/imagename.
Ex:
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<ImageView
android:id=”@+id/button1”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:src=”@drawable/one”/>
</LinearLayout>

Switching States with Toggle Button:


 As the name suggest, ToggleButton toggles between the two states.
 A ToggleButton can only be in one state out of two mutually exclusive states.
 To display a ToggleButton we use <ToggleButton> tag.
 By using the below code we can implement switching states of application.

activity_toggle_button.xml

C.B.I.T-C.S.E Page 25
Unit-III

<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<ToggleButton  
android:id="@+id/playstop_btn"  
android:layout_width="wrap_content"  
android:layout_height="wrap_content"  
android:text="ToggleButton"  
android:textOn="Play"  
android:textOff="Stop" />
<TextView  
android:id="@+id/tv"  
android:layout_width="wrap_content"  
android:layout_height="wrap_content"  
android:text="Select the play button"/>
</Linear Layout>

ToggleButtonAppActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.view.View;
import android.view.View.OnClickListener;

public class ToggleButtonAppActivity extends Activity


{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toggle_button_app);
final TextView resp=(TextView) this.findViewById(R.id.tv);
final ToggleButton tb=(ToggleButton) findViewById(R.id.playstop_btn);
tb.setChecked(true);
tb.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
C.B.I.T-C.S.E Page 26
Unit-III

{
if(tb.isChecked())
{
resp.setText(“Stop button is displaying”);
}
else
{
resp.setText(“Play button is displaying”)
}
}
});
}}

Creating an Image Switcher Application


For creating an Image switcher application we need to use Toggle Button and for displaying
images first we need to add those images to the drawable folder. Assume that we have already
added 4 images called one.jpes,two.jpeg,three.jpeg,four.jpeg. After adding the images to display
those images we need to use ImageView tag in xml.
The following code is used for creating an ImageSwitcher Application.
activity_disp_image_app.xml
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<ToggleButton  
android:id="@+id/playstop_btn"  
android:layout_width="wrap_content"  
android:layout_height="wrap_content"  
android:text="ToggleButton"  
android:textOn="Previous Image"  
android:textOff="Next Image" />
<ImageView  
android:id="@+id/iv"  
android:layout_width="wrap_content"  
android:layout_height="wrap_content"  
android:src="@drawable/one”/>
</Linear Layout>

DispImageAppActivity.java

C.B.I.T-C.S.E Page 27
Unit-III

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.view.View;
import android.view.View.OnClickListener;

public class DispImageAppActivity extends Activity


{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disp_image_app);
final ImageView image=(ImageView) this.findViewById(R.id.iv);
final ToggleButton tb=(ToggleButton) findViewById(R.id.playstop_btn);
tb.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if(tb.isChecked())
{
image.setImageResource(“R.drawable.two”);
}
else
{
image.setImageResource(“R.drawable.one”)
}
}
});
}}

Playing Audio:
Here we are going to creating an application called “PlayAudioApp”. For creating this
application first we need to add audio to the application.
The audio need to be add to the res/raw folder. This raw folder we need to create
manually. For that select and give right click to the res folder. Then you will find new folder
option. Click on that then one dialogue box appears there you can give the name of the folder as
“raw” and click on Finish button.

C.B.I.T-C.S.E Page 28
Unit-III

For adding audio to the raw folder first go to the audio location where it is available and
then copy the audio and select raw folder give right click there you will find an option called
paste. By clicking on that paste option your audio is going to be add to the raw folder.
To work with audio in android we can use a default class called “Media Player”.
This class only having the definitions for starting(start()) the audio play and stopping (pause())
the audio play.
The below code can be used for creating PlayAudioApp.

activity_play_audio_app.xml
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<ToggleButton  
android:id="@+id/playstop_btn"  
android:layout_width="wrap_content"  
android:layout_height="wrap_content"  
android:text="ToggleButton"  
android:textOn="Play"  
android:textOff="Stop" />
<TextView  
android:id="@+id/tv"  
android:layout_width="wrap_content"  
android:layout_height="wrap_content"/>
</Linear Layout>
PlayAudioAppActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.view.View;
import android.view.View.OnClickListener;
import android.media.MediaPlayer;
public class PlayAudioAppActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_audio_app);
final TextView resp=(TextView) this.findViewById(R.id.tv);
C.B.I.T-C.S.E Page 29
Unit-III

final ToggleButton tb=(ToggleButton) findViewById(R.id.playstop_btn);


resp.setText(“Select Play button to play audio”);
final MediaPlayer mp=MediaPlayer.create(PlayAudioAppActivity.this, R.raw.song1);
tb.setOnClickListener(View v)
{
if(tb.isChecked())
{
resp.setText(“Select the stop button to stop audio”);
mp.start();
}
else
{
resp.setText(“Select the Play button to start audio”);
mp.pause();
}
}
});
}
}

Playing Video:
For Creating the video Player application first we need to Add the video to the SD Card.

For adding the video to SD card we need to follow the below steps:

1) We need to start the emulator/AVD


2) Get back to android studio-- window-open perspective- DDMS(Dalvik Debug
Monitor system) file explorer is going to be open
3) file explorer consit of so many folders… we need to select the folder mnt…
4) by click on this mnt folder you will find SDCARD.

After adding the video to SD card we need to use two components

1) <VideoView> tag- used for creating video player view. We need to write this is Xml
Program.

2) MediaController Package which consist of controls for play,pause,forward, rewind .

Ex: Video Palyerapp

Activity_play_video_app.xml:

C.B.I.T-C.S.E Page 30
Unit-III

<LinearLayout
Xmlns: Android=”http://schemas.android.com/apk/res/android”
Android:layout_width=”Match_parent”
Android:layout_height=”Match_parent”>
<VideoView
Android:layout_width=”500px”
Android:layout_height=” 300 px”
Android:id=”@+id/vid”/>
<Button
Android:layout_width=”wrap_content”
Android:layout_height=” wrap_content”
Android:text=”Play Video”
Android:id=”@+id/playvid”/>
</LinearLayout>

PlayvideoAppActivity.java

Import android.app.Activity;
Import android.os.Bundle;
Import android.view.View;
Import android.widget.Button;
Import android.view.View.OnClickListener;
Import android.widget.MediaController;
Import android.widget.VideoView;

Public class playVideoAppActivity extends Activity


{
@Override
Public void onCreate(Bundle savedInstanceState)
{
Super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video_app);
Button playvidbtn=(Button)findViewById(R.id.playvid);
Playvidbtn.setOnClickListener(new OnClickListener()
{
Public void onClick(view View)
{
VideoView vv=(VideoView)findViewById(R.id.vid);
vv.setMediaController( new MediaCotroller(PlayvideoappActivity.this)
vv.setVideoPath(“sdcard/video1.mp4”);
vv.requestFocus();
vv.start();
}
});
}
}

Scrolling through ScrollView:

C.B.I.T-C.S.E Page 31
Unit-III

A ScrollView is a special type of control that sets up a vertical scrollbar in a view container. This
control is used when we try to display Views that are too long to be accommodated in a single
screen. The Scrollview can have one child view, so usually a View container layout is used as a
child which in turn contains other child controls that we want to scroll through.

To display the controls which are more larger than the size of the display using ScrollView we
need to use the fillViewPort attribute. This attribute make the scrollview to expand to display
large size images and makes to shrink the display to display less size images. But this can
possible when you set the value of fillViewPort as “true”.

The following code we need to write for achieving scrollbar.

<ScrollView
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:fillViewPort=”true”
android:orientation=”vertical”>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<ImageView  
android:id="@+id/iv"  
android:layout_width="250dip"  
android:layout_height="200 dip"  
android:src="@drawable/one”/>
</Linear Layout>
</ScrollView>

Displaying Progress with ProgressBar:

We can display the android progress bar dialog box to display the status of work being done e.g.
downloading file, analyzing status of work etc.

In this example, we are displaying the progress dialog for dummy file download operation.

Here we are using android.app.ProgressDialog class to show the progress bar. Android ProgressDialog is the
subclass of AlertDialog class.

C.B.I.T-C.S.E Page 32
Unit-III

The ProgressDialog class provides methods to work on progress bar like setProgress(), setMessage(),


setProgressStyle(), setMax(), show() etc. The progress range of Progress Dialog is 0 to 10000.

Let's see a simple example to display progress bar in android.


1. ProgressDialog progressBar = new ProgressDialog(this);  
2. progressBar.setCancelable(true);//you can cancel it by pressing back button  
3. progressBar.setMessage("File downloading ...");  
4. progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
5. progressBar.setProgress(0);//initially progress is 0  
6. progressBar.setMax(100);//sets the maximum value 100  
7. progressBar.show();//displays the progress bar  

Android Progress Bar Example by ProgressDialog


Let's see a simple example to create progress bar using ProgressDialog class.

activity_main.xml

Drag one button from the pallete, now the activity_main.xml file will look like this:

File: activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MainActivity" >  
  
    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentTop="true"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="116dp"  
        android:text="download file" />  

C.B.I.T-C.S.E Page 33
Unit-III

  
</RelativeLayout>  

Activity class

Let's write the code to display the progress bar dialog box.

File: MainActivity.java

import android.app.ProgressDialog;  
import android.os.Handler;  
import android.support.v7.app.AppCompatActivity;  
import android.os.Bundle;  
import android.view.View;  
import android.widget.Button;  
  
public class MainActivity extends AppCompatActivity {  
    Button btnStartProgress;  
    ProgressDialog progressBar;  
    private int progressBarStatus = 0;  
    private Handler progressBarHandler = new Handler();  
    private long fileSize = 0;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        addListenerOnButtonClick();  
    }  
    public void addListenerOnButtonClick() {  
        btnStartProgress = findViewById(R.id.button);  
        btnStartProgress.setOnClickListener(new View.OnClickListener(){  
  
            @Override  
            public void onClick(View v) {  
                // creating progress bar dialog  

C.B.I.T-C.S.E Page 34
Unit-III

                progressBar = new ProgressDialog(v.getContext());  
                progressBar.setCancelable(true);  
                progressBar.setMessage("File downloading ...");  
                progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
                progressBar.setProgress(0);  
                progressBar.setMax(100);  
                progressBar.show();  
                //reset progress bar and filesize status  
                progressBarStatus = 0;  
                fileSize = 0;  
  
                new Thread(new Runnable() {  
                    public void run() {  
                        while (progressBarStatus < 100) {  
                            // performing operation  
                            progressBarStatus = doOperation();  
                            try {  
                                Thread.sleep(1000);  
                            } catch (InterruptedException e) {  
                                e.printStackTrace();  
                            }  
                            // Updating the progress bar  
                            progressBarHandler.post(new Runnable() {  
                                public void run() {  
                                    progressBar.setProgress(progressBarStatus);  
                                }  
                            });  
                        }  
                        // performing operation if file is downloaded,  
                        if (progressBarStatus >= 100) {  
                            // sleeping for 1 second after operation completed  
                            try {  
                                Thread.sleep(1000);  
                            } catch (InterruptedException e) {  

C.B.I.T-C.S.E Page 35
Unit-III

                                e.printStackTrace();  
                            }  
                            // close the progress bar dialog  
                            progressBar.dismiss();  
                        }  
                    }  
                }).start();  
            }//end of onClick method  
        });  
    }  
    // checking how much file is downloaded and updating the filesize  
    public int doOperation() {  
        //The range of ProgressDialog starts from 0 to 10000  
        while (fileSize <= 10000) {  
            fileSize++;  
            if (fileSize == 1000) {  
                return 10;  
            } else if (fileSize == 2000) {  
                return 20;  
            } else if (fileSize == 3000) {  
                return 30;  
            } else if (fileSize == 4000) {  
                return 40; // you can add more else if   
            }   
         /* else { 
                return 100; 
            }*/  
        }//end of while  
            return 100;  
    }//end of doOperation  
}  

Output:

C.B.I.T-C.S.E Page 36
Unit-III

C.B.I.T-C.S.E Page 37

You might also like