0% found this document useful (0 votes)
10 views

UNIT-III

Unit 3 of the Mobile Application Development course covers the building blocks for Android application design, focusing on various layout types such as Linear, Relative, Absolute, and Frame Layouts. Each layout type is described with its attributes and examples of XML code for implementation. The unit also discusses how to manage views and resources, including media resources and user interface elements.

Uploaded by

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

UNIT-III

Unit 3 of the Mobile Application Development course covers the building blocks for Android application design, focusing on various layout types such as Linear, Relative, Absolute, and Frame Layouts. Each layout type is described with its attributes and examples of XML code for implementation. The unit also discusses how to manage views and resources, including media resources and user interface elements.

Uploaded by

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

Mobile Application Development Unit-III

Unit 3: Building Blocks for Android Application Design:

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

INTRODUCTION TO LAYOUTS
Layouts are basically containers for other items known as Views, which are displayed on
the screen. Layouts help manage and arrange views as well. Layouts are defined in the form of
XML files that cannot be changed by our code during runtime.
Android Layout Managers

Layout Manager Description


LinearLayout Organizes its children either horizontally or vertically
RelativeLayout Organizes its children relative to one another or to the parent

AbsoluteLayout Each child control is given a specific location within the bounds of
the container
FrameLayout Displays a single view, that is the next view replaces the previous
view and hence is used to dynamically change the children in the
layout.
TableLayout Organizes its children in tabular form
GridLayout Organizes its children in grid format

(i). Linear Layout


Android LinearLayout is a view group that aligns all children in either vertically or horizontally.

LINEAR LAYOUT

Page 1
Mobile Application Development Unit-III

LinearLayout Attributes
Following are the important attributes specific to LinearLayout −

Sr.No Attribute & Description

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

android:baselineAligned
2 This must be a boolean value, either "true" or "false" and prevents the layout from
aligning its children's baselines.

android:baselineAlignedChildIndex
3 When a linear layout is part of another layout that is baseline aligned, it can specify
which of its children to baseline align.

android:divider
4 This is drawable to use as a vertical divider between buttons. You use a color value,
in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

android:gravity
This specifies how an object should position its content, on both the X and Y axes.
5
Possible values are top, bottom, left, right, center, center_vertical, center_horizontal
etc.

android:orientation
6 This specifies the direction of arrangement and you will use "horizontal" for a row,
"vertical" for a column. The default is horizontal.

android:weightSum
7
Sum up of child weight

This Application will take you through simple steps to show how to create your own
Android application using Linear Layout.
Following will be the content of activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
tools:context="in.kvsw.linearlayout.MainActivity">

Page 2
Mobile Application Development Unit-III

<Button
android:id="@+id/btnStartService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="start_service"/>
<Button
android:id="@+id/btnPauseService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="pause_service"/>
<Button
android:id="@+id/btnStopService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="stop_service"/>
</LinearLayout>

MainActivity.java
packagein.kvsw.linearlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Page 3
Mobile Application Development Unit-III

OUTPUT:
I assume you had created your AVD while doing environment setup. To run the app from
Android Studio, click Run icon from the toolbar. Android Studio installs the app AVD and
starts it and if everything is fine with setup and application, it will display following Emulator
window −

Now let's change the orientation of Layout as android:orientation="horizontal" and try to run
the same application, it will give following screen −

Page 4
Mobile Application Development Unit-III

(ii) Relative Layout


Android RelativeLayout enables you to specify how child views are positioned relative to
each other. The position of each view can be specified as relative to sibling elements or relative
to the parent.

RELATIVE LAYOUT
RelativeLayout Attributes
Following are the important attributes specific to RelativeLayout −

Sr.No. Attribute & Description

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

2 android:gravity
This specifies how an object should position its content, on both the X and Y axes.
Possible values are top, bottom, left, right, center, center_vertical, center_horizontal
etc.

3 android:ignoreGravity
This indicates what view should not be affected by gravity.

Page 5
Mobile Application Development Unit-III

Few of the important attributes are given below −

Sr.No. Attribute & Description

1 android:layout_above
Positions the bottom edge of this view above the given anchor view ID and must be a
reference to another resource, in the form "@[+][package:]type:name"

2 android:layout_alignBottom
Makes the bottom edge of this view match the bottom edge of the given anchor view
ID

3 android:layout_alignLeft
Makes the left edge of this view match the left edge of the given anchor view ID

4 android:layout_alignParentBottom
If true, makes the bottom edge of this view match the bottom edge of the parent.
Must be a boolean value, either "true" or "false".

5 android:layout_alignParentEnd
If true, makes the end edge of this view match the end edge of the parent. Must be a
boolean value, either "true" or "false".

6 android:layout_alignParentLeft
If true, makes the left edge of this view match the left edge of the parent. Must be a
boolean value, either "true" or "false".

7 android:layout_alignParentRight
If true, makes the right edge of this view match the right edge of the parent. Must be
a boolean value, either "true" or "false".

8 android:layout_alignParentStart
If true, makes the start edge of this view match the start edge of the parent. Must be a
boolean value, either "true" or "false".

9 android:layout_alignParentTop
If true, makes the top edge of this view match the top edge of the parent. Must be a
boolean value, either "true" or "false".

10 android:layout_alignRight
Makes the right edge of this view match the right edge of the given anchor view ID

11 android:layout_alignStart
Makes the start edge of this view match the start edge of the given anchor view ID

12 android:layout_alignTop
Makes the top edge of this view match the top edge of the given anchor view ID

Page 6
Mobile Application Development Unit-III

13 android:layout_below
Positions the top edge of this view below the given anchor view ID

14 android:layout_centerHorizontal
If true, centers this child horizontally within its parent. Must be a boolean value,
either "true" or "false".

15 android:layout_centerInParent
If true, centers this child horizontally and vertically within its parent. Must be a
boolean value, either "true" or "false".

16 android:layout_centerVertical
If true, centers this child vertically within its parent. Must be a boolean value, either
"true" or "false".

17 android:layout_toEndOf
Positions the start edge of this view to the end of the given anchor view ID

18 android:layout_toLeftOf
Positions the right edge of this view to the left of the given anchor view ID

19 android:layout_toRightOf
Positions the left edge of this view to the right of the given anchor view ID

20 android:layout_toStartOf
Positions the end edge of this view to the start of the given anchor view ID

This Application will take you through simple steps to show how to create your own Android
application using Relative Layout.

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

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
tools:context="in.kvsw.relativelayout.MainActivity">

Page 7
Mobile Application Development Unit-III

<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/reminder" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentStart="true"
android:layout_below="@+id/name">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button2" />
</LinearLayout>
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="action_settings">Settings</string>
<string name="reminder">Enter your name</string>
</resources>

Page 8
Mobile Application Development Unit-III

MainActivity.java
package in.kvsw.relativelayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

OUTPUT:
I assume you had created your AVD while doing environment setup. To run the app from
Android Studio, click Run icon from the toolbar. Android Studio installs the app AVD and
starts it and if everything is fine with setup and application, it will display following Emulator
window −

Page 9
Mobile Application Development Unit-III

(iii) Absolute Layout


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

ABSOLUTE LAYOUT

AbsoluteLayout Attributes

Sr.No Attribute & Description

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

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

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

Public Constructors

AbsoluteLayout(Context context)

AbsoluteLayout(Context context, AttributeSet attrs)

AbsoluteLayout(Context context, AttributeSet attrs, int defStyleAttr)

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

Page
10
Mobile Application Development Unit-III

This Application will take you through simple steps to show how to create Android application
using absolute layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout 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="fill_parent"
android:layout_height="fill_parent">
tools:context="in.kvsw.absolutelayout.MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="370dp"
android:layout_height="42dp"
android:background="#00ffff"
android:gravity="center"
android:text="Absolute Layout"
android:textColor="#ff0000"
android:textSize="25dp"
android:textStyle="bold"
tools:layout_editor_absoluteX="17dp"
tools:layout_editor_absoluteY="18dp" />
<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="495px"
android:layout_y="361px" />
</AbsoluteLayout>

Page
11
Mobile Application Development Unit-III

MainActivity.java
packagein.kvsw.absolutelayout;
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:
I assume you had created your AVD while doing environment setup. To run the app from
Android Studio, click Run icon from the toolbar. Android Studio installs the app AVD and
starts it and if everything is fine with setup and application, it will display following Emulator
window −

Page
12
Mobile Application Development Unit-III

(iv) Frame Layout


Frame Layout is designed to block out an area on the screen to display a single item.
Generally, FrameLayout should be used to hold a single child view, because it can be difficult
to organize child views in a way that's scalable to different screen sizes without the children
overlapping each other.

You can, however, add multiple children to a FrameLayout and control their position
within the FrameLayout by assigning gravity to each child, using the
android:layout_gravity attribute.

Following is the pictorial representation of frame layout in android applications.

FRAME LAYOUT

In android, FrameLayout will act as a placeholder on the screen and it is used to hold
a single child view.
In FrameLayout, the child views are added in a stack and the most recently added
child will show on the top. We can add multiple children views to FrameLayout and control
their position by using gravity attributes in FrameLayout.
FrameLayout Attributes

Sr.No Attribute & Description

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

2 android:foreground
This defines the drawable to draw over the content and possible values may be a
color value, in the form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

3 android:foregroundGravity
Defines the gravity to apply to the foreground drawable. The gravity defaults to
fill. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.

Page
13
Mobile Application Development Unit-III

4 android:measureAllChildren
Determines whether to measure all children or just those in the VISIBLE or
INVISIBLE state when measuring. Defaults to false.

Example
This example will take you through simple steps to show how to create your own Android
application using frame layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:orientation="vertical"
tools:context="in.kvsw.framelayout.MainActivity">
<ImageView
android:id="@+id/imgvw1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/flimg" />
<TextView
android:id="@+id/txtvw1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:background="#4C374A"
android:padding="5dp"
android:text="Welcome to KVSW"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<TextView
android:id="@+id/txtvw2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Page
14
Mobile Application Development Unit-III

android:layout_gravity="right|bottom"
android:background="#AA000000"
android:padding="10dp"
android:text="KURNOOL,AP"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</FrameLayout>

We used ImageView to show the image (flimg) from drawable folder in framelayout. So add
your image to drawable folder and replace @drawable/flimg path with your image path.
1.Open your project in Android Studio.
2.Click on res.
3.Right click on drawable.
4.Click on Show in Explorer.
5.Double click on drawable folder.
6.Copy your image file in it and rename as your wish.
7.Now write your image file name after @drawable/

MainActivity.java.
package in.kvsw.framelayout;
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);
}
}

Page
15
Mobile Application Development Unit-III

OUTPUT
I assume you had created your AVD while doing environment setup. To run the app from
Android Studio, click Run icon from the toolbar. Android Studio installs the app AVD and
starts it and if everything is fine with setup and application, it will display following Emulator
window −

(v) Table Layout


Android TableLayout going to be arranged groups of views into rows and
columns. You will use the <TableRow> element to build a row in the table. Each row has
zero or more cells; each cell can hold one View object.

TableLayout containers do not display border lines for their rows, columns, or cells.

Page
16
Mobile Application Development Unit-III

TableLayout Attributes
Following are the important attributes specific to TableLayout −

Sr.No. Attribute & Description

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

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

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

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

Example
This example will take you through simple steps to show how to create your own Android
application using Table Layout

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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:stretchColumns="*"
tools:context="in.kvsw.tablelayout.MainActivity">
<!-- 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">

Page
17
Mobile Application Development Unit-III

<!-- 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="Col-1 and 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"
android:padding="18dip"
android:text="Col-2 and Text 2"
android:textColor="#000"
android:textSize="12dp" />
<TextView
android:id="@+id/simpleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFff00"
android:padding="18dip"
android:text="Col-3 and Text 3"
android:textColor="#000"
android:textSize="12dp" />
</TableRow>
</TableLayout>

Page
18
Mobile Application Development Unit-III

MainActivity.java
packagein.kvsw.tablelayout;
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:
I assume you had created your AVD while doing environment setup. To run the app
from Android Studio, click Run icon from the toolbar. Android Studio installs the app AVD
and starts it and if everything is fine with setup and application, it will display following
Emulator window −

Page
19
Mobile Application Development Unit-III

(VI) Grid Layout


Android GridView shows items in two-dimensional scrolling grid (rows &
columns) and the grid items are not necessarily predetermined but they automatically inserted
to the layout using a ListAdapter

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

GridView Attributes

Sr.No Attribute & Description

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.

3 android:gravity

Page
20
Mobile Application Development Unit-III

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, such as "100" or
5
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.

Example
This example will take you through simple steps to show how to create your own Android
application using GridView.
activity_main.xml

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


<GridView 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:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
Page
21
Mobile Application Development Unit-III

android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="spacingWidth"
android:gravity="center"
tools:context="in.kvsw.gridlayout.MainActivity" />

MainActivity.java

package in.kvsw.gridlayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.GridLayout;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
}
}

ImageAdapter.java
package in.kvsw.gridlayout;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

Page
22
Mobile Application Development Unit-III

public class ImageAdapter extends BaseAdapter


{
private Context mContext;
// Constructor
public ImageAdapter(Context c)
{
mContext = c;
}
public int getCount()
{
return mThumbIds.length;
}
public Object getItem(int position)
{
return null;
}
public long getItemId(int position)
{
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null)
{
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(320, 180));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(1, 1, 1, 1);
}
else
{
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
Page
23
Mobile Application Development Unit-III

// Keep all Images in array


public Integer[] mThumbIds =
{
R.drawable.sample_1, R.drawable.sample_2,
R.drawable.sample_3,R.drawable.sample_4,
R.drawable.sample_5, R.drawable.sample_6,
R.drawable.sample_7, R.drawable.sample_0,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6
};
}
OUTPUT:
I assume you had created your AVD while doing environment setup. To run the app from
Android Studio, click Run icon from the toolbar. Android Studio installs the app AVD and
starts it and if everything is fine with setup and application, it will display following Emulator
window −

Page
24
Mobile Application Development Unit-III

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.
The Screen Orientation is the attribute of activity element. The orientation of android activity
can be portrait, landscape, sensor, unspecified etc. You need to define it in the
AndroidManifest.xml file.
Syntax:
<activity android:name="package_name.Your_ActivityName" android:screenOrientation="orie
ntation_type">
</activity>

The common values for Screen Orientation attribute are as follows:

Value Description

unspecified It is the default value. In such case, system chooses the orientation.

portrait taller not wider

landscape wider not taller

sensor Orientation is determined by the device orientation sensor.

Page
25
Mobile Application Development Unit-III

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.

Page
26
Mobile Application Development Unit-III

Android Portrait and Landscape mode screen orientation example


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
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="fill_parent"
android:layout_height="fill_parent"
tools:context="in.kvsw.screenorientation.MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="370dp"
android:layout_height="42dp"
android:background="#00ffff"
android:gravity="center"
android:text="Screen Orientation-Landscape"
android:textColor="#ff0000"
android:textSize="25dp"
android:textStyle="bold"
tools:layout_editor_absoluteX="17dp"
tools:layout_editor_absoluteY="18dp" />
<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="495px"
android:layout_y="361px" />
</AbsoluteLayout>
Page
27
Mobile Application Development Unit-III

File: MainActivity.java
package in.kvsw.screenorientation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

AndroidManifest.xml

In AndroidManifest.xml file add the Screen Orientation attribute in activity and provides its
orientation. In this example, we provide "portrait" / "landscape" orientation for MainActivity

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.kvsw.screenorientation">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait/landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

Page
28
Mobile Application Development Unit-III

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


</intent-filter>
</activity>
</application>
</manifest>

Output:

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.
Resources are broadly divided into three categories—
 values,
 drawable, and
 layout
Resources 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, as
shown below.
Page
29
Mobile Application Development Unit-III

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

Page
30
Mobile Application Development Unit-III

 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
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 values directory. The filename can be anything, but most commonly, the string resources file
is named strings.xml. Remember, the resource filenames should contain only lowercase letters,
numbers, period (.), and underscore (_) symbols.
Let’s modify the strings.xml file to appear as shown below
<resources>
<string name="app_name">ValueResources</string>
<string name="str_name">Dr.K.V.S.W Engineering College</string>
<string name="str_address">Opp Dupadu Railway Station, NH-44, Kurnool</string>
<string name="str_message"><b>Welcome to KVSW!</b></string>
</resources>

Page
31
Mobile Application Development Unit-III

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.
We can use the string resources of the preceding XML file in other resource files by using the
following syntax:
@string/resource_ID
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.valueresources.MainActivity">
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ff0000"
android:textSize="25dp"
android:textStyle="bold"
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>

Page
32
Mobile Application Development Unit-III

MainActivity.java
package in.kvsw.valueresources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String strAddress=getString(R.string.str_address);
TextView addressView=(TextView)findViewById(R.id.address_view);
addressView.setText(strAddress);
}
}
OUTPUT:

Page
33
Mobile Application Development Unit-III

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.
activity_main.xml on Adding the ImageViewControl

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


<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.drawableresources.MainActivity">
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/logo"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

Page
34
Mobile Application Development Unit-III

MainActivity.java

package in.kvsw.drawableresources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image = (ImageView) findViewById(R.id.image_toview);
image.setImageResource(R.drawable.logo);
}
}
OUTPUT:

Page
35
Mobile Application Development Unit-III

SWITCHING STATES WITH TOGGLE BUTTONS


As the name suggests, the ToggleButton toggles between the two states, something like a
radio button. A ToggleButton can only be in one state out of two mutually exclusive states, for
example, On and Off.
To display a ToggleButton, we use the <ToggleButton> tag in the layout file. To set the
text for the button, the two attributes android:textOn and android:textOff are used.
The default values for the two attributes are ON and OFF, respectively. The following
code shows how to create a toggle button using the ToggleButton tag:
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Play"
android:textOff="Stop" />
This code block defines a toggle button that shows the text Play in the On state and shows Stop in
the Off state.
activity_main.xml on Adding the ToggleButton Controls and Button

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


<android.support.constraint.ConstraintLayout
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"
tools:context="in.kvsw.togglebutton.MainActivity">

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="80dp"
android:text="ToggleButton"
android:textOff="Off"
android:textOn="On"
app:layout_constraintEnd_toStartOf="@+id/toggleButton2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

Page
36
Mobile Application Development Unit-III

<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="60dp"
android:layout_marginTop="80dp"
android:text="ToggleButton"
android:textOff="Off"
android:textOn="On"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="144dp"
android:layout_marginLeft="148dp"
android:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>

MainActivity.java

package in.kvsw.togglebutton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity
{
private ToggleButton toggleButton1, toggleButton2;
private Button buttonSubmit;

Page
37
Mobile Application Development Unit-III

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick()
{
//Getting the ToggleButton and Button instance from the layout xml file
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
buttonSubmit=(Button)findViewById(R.id.button);
//Performing action on button click
buttonSubmit.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
StringBuilder result = new StringBuilder();
result.append("ToggleButton1 : ").append(toggleButton1.getText());
result.append("\nToggleButton2 : ").append(toggleButton2.getText());
//Displaying the message in toast
Toast.makeText(getApplicationContext(),
result.toString(),Toast.LENGTH_LONG).show();
}
});
}
}

Page
38
Mobile Application Development Unit-III

OUTPUT:

CREATING AN IMAGE SWITCHER APPLICATION


When the ToggleButton is clicked, the image displayed in the ImageView control
changes. After we click the ToggleButton again, the previous image is redisplayed in
the ImageView control.
Because we want the application to switch images, we need to add one more image to the
application.

activity_main.xml on Adding a ToggleButton and Assigning an Image to


the ImageView Control
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="in.kvsw.imageswitcher.MainActivity">
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true" />
Page
39
Mobile Application Development Unit-III

<ToggleButton android:id="@+id/change_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Previous Image"
android:textOff="Next Image"
android:layout_gravity="center"
android:layout_marginTop="10dip" />
</LinearLayout>

MainActivity.java

package in.kvsw.imageswitcher;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView image = (ImageView) findViewById(R.id.image_toview);
final ToggleButton
changeButton=(ToggleButton)findViewById(R.id.change_image);
changeButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (changeButton.isChecked())
{
image.setImageResource(R.drawable.logo);
}

Page
40
Mobile Application Development Unit-III

else
{
image.setImageResource(R.drawable.logo1);
}
}
});
}
}
OUTPUT:

(left) An image displayed through the ImageView control with a ToggleButton below it,
and (right) the image in the ImageView switches when the ToggleButton is selected.

PLAYING AUDIO
In this section, we learn to play audio in Android applications. We also learn the methods
used to pause and resume the audio. Let’s make a new Android project called PlayAudio. The
audio that we want to play needs to be added to this application.
Adding Audio to the Application
The audio file that we want to play must be located in the res/raw folder of our
application. The raw folder isn’t created automatically, so we need to create it manually.
The raw folder is a special folder that is not processed at all; hence the content of the files copied
in this folder is retained. Right-click the res folder in the Package Explorer window and
select New, Folder. In the dialog box that opens, enter the name of the new folder as raw and
click the Finish button.
Page
41
Mobile Application Development Unit-III

We can play and control the audio files in android by the help of MediaPlayer class.
Here, we are going to see a simple example to play the audio file. In the next page, we will see the
example to control the audio playback like start, stop, pause etc.
MediaPlayer class
The android.media.MediaPlayer class is used to control the audio or video files.
Methods of MediaPlayer class

Method Description

public void setDataSource(String path) sets the data source (file path or http url)
to use.

public void prepare() prepares the player for playback


synchronously.

public void start() it starts or resumes the playback.

public void stop() it stops the playback.

public void pause() it pauses the playback.

public boolean isPlaying() checks if media player is playing.

public void seekTo(int millis) seeks to specified time in miliseconds.

public void setLooping(boolean looping) sets the player for looping or non-
looping.

public boolean isLooping() checks if the player is looping or non-


looping.

public void selectTrack(int index) it selects a track for the specified index.

public int getCurrentPosition() returns the current playback position.

public int getDuration() returns duration of the file.

public void setVolume(float leftVolume,float sets the volume on this player.


rightVolume)

Android MediaPlayer Application of controlling the audio


Let's see a simple Application to start, stop and pause the audio play.
activity_main.xml
Drag three buttons from pallete to start, stop and pause the audio play. Now the xml file will look
like this:

Page
42
Mobile Application Development Unit-III

File: MainActivity.java
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:text="Audio Controller" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="48dp"
android:text="start" />
<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="pause" />

Page
43
Mobile Application Development Unit-III

<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button2"
android:layout_toRightOf="@+id/button2"
android:text="stop" />
</RelativeLayout>

Activity class

Let's write the code to start, pause and stop the audio player.

File: MainActivity.java
package com.example.audioplay;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity
{
Button start,pause,stop;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);
stop=(Button)findViewById(R.id.button3);
//creating media player
final MediaPlayer mp=new MediaPlayer();

Page
44
Mobile Application Development Unit-III

try
{
//you can change the path, here path is external directory(e.g. sdcard) /Music/
maine.mp3
mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/
maine.mp3");
mp.prepare();
}
catch(Exception e)
{
e.printStackTrace();
}
start.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mp.start();
}
});
pause.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mp.pause();
}
});
stop.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mp.stop();
}
});
}
}

Page
45
Mobile Application Development Unit-III

Output:

PLAYING VIDEO

By the help of MediaController and VideoView classes, we can play the video files in android.
MediaController class
The android.widget.MediaController is a view that contains media controls like play/pause,
previous, next, fast-forward, rewind etc.
VideoView class
The android.widget.VideoView class provides methods to play and control the video player. The
commonly used methods of VideoView class are as follows:

Method Description

public void setMediaController(MediaController sets the media controller to the video


controller) view.

public void setVideoURI (Uri uri) sets the URI of the video file.

public void start() starts the video view.

public void stopPlayback() stops the playback.

public void pause() pauses the playback.

public void suspend() suspends the playback.

Page
46
Mobile Application Development Unit-III

public void resume() resumes the playback.

public void seekTo(int millis) seeks to specified time in miliseconds.


activity_main.xml
Drag the VideoView from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
<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" >
<VideoView android:id="@+id/video"
android:layout_width="320dip"
android:layout_height="240dip"/>
<Button android:id="@+id/playvideo"
android:text="Play Video"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
</LinearLayout>
Activity class
Let's write the code of to play the video file. Here, we are going to play 1.mp4 file located inside
the sdcard/media directory.
File: MainActivity.java
package com.androidunleashed.playvideoapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.MediaController;
import android.widget.VideoView;
public class PlayVideoAppActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)

Page
47
Mobile Application Development Unit-III

{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video_app);
Button playVideoButton=(Button)findViewById(R.id.playvideo);
playVideoButton.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
VideoView videoView=(VideoView)findViewById(R.id.video);
videoView.setMediaController(new
MediaController(PlayVideoAppActivity.this));
videoView.setVideoPath("sdcard/video.mp4");
videoView.requestFocus();
videoView.start();
}
});
}
}
OUTPUT:

Page
48
Mobile Application Development Unit-III

DISPLAYING PROGRESS WITH PROGRESSBAR


Certain tasks, such as downloading a file, installing software, executing complex queries,
and playing audio and video, take time to execute. While executing such tasks, we need to
continually inform the user about the task progress by displaying a progress indicator.
The ProgressBar is a control commonly used for displaying the progress of execution
of tasks.
The default mode of the ProgressBar view is a circular indicator that animates to show that
a task is active but doesn’t show actual progress. This icon is used when there is no specific
duration for completion of the task.
A more informative solution is a horizontal progress bar that displays an indicator
showing the amount of a task that is completed (or is left to complete).
To make the ProgressBar display in the form of a horizontal bar, set its style attribute
to @android:style/Widget.ProgressBar.Horizontal, as shown in this example:
<ProgressBar android:id="@+id/progressbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal" />
The following styles can be applied to the ProgressBar:
 Widget.ProgressBar.Horizontal
 Widget.ProgressBar.Small
 Widget.ProgressBar.Large
 Widget.ProgressBar.Inverse
 Widget.ProgressBar.Small.Inverse
 Widget.ProgressBar.Large.Inverse
The ProgressBar for Widget.ProgressBar.Horizontal, Widget.ProgressBar.Small,
and Widget.ProgressBar appears as shown in Figure 4.24 (left, middle, and right, respectively).

Figure 4.24. (left) Horizontal style ProgressBar, (middle) small style ProgressBar, and (right)
large style ProgressBar

Page
49
Mobile Application Development Unit-III

activitymain.xml on Adding the ProgressBar Controls


<?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"
tools:context="in.kvsw.progressbar.MainActivity">
<Button
android:id="@+id/button"
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" />
</RelativeLayout>
MainActivity.java
package in.kvsw.progressbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.ProgressDialog;
import android.os.Handler;
public class MainActivity extends AppCompatActivity
{
Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private long fileSize = 0;
@Override

Page
50
Mobile Application Development Unit-III

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
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()
Page
51
Mobile Application Development Unit-III

{
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)
{
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)
Page
52
Mobile Application Development Unit-III

{
return 40; // you can add more else if
}
}//end of while
return 100;
}//end of doOperation
}
OUTPUT:

(left) ProgressBar on application startup, and (right) ProgressBar showing the duration of audio
played

USING ASSETS
We have already seen how resources are used in Android applications.
The external files containing information such as strings, images, and audio that reside in
the res/ folder are considered resources.
Besides the res/ directory, Android provides another directory, assets/, where we can keep
asset files to be included in our application.
The difference between resources and assets is that the resources are accessible in an
Android application through the resource IDs generated in the R.java file.
Android automatically generates an R.java file that contains the IDs of the resources
found in res/folder, making it possible to access them through Java code. Content placed in
the assets/ directory is maintained in raw file format, and no IDs are generated for these files.

Page
53
Mobile Application Development Unit-III

To read the content from the assets/ folder in an Android application, we use
the AssetManager, which reads the content from the external files in the form of a stream of
bytes.
Listing 4.43. Code in Layout File activity_main.xml on Adding the TextViewControl
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
tools:context="in.kvsw.assets.MainActivity">

<TextView
android:id="@+id/file_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dip"
android:textStyle="bold" />
</LinearLayout>

info.txt
Welcome to Dr K V Subba Reddy College of Engineering for Women, Kurnool

We can see that the layout file activity_assets_app.xml contains a file_view TextViewcontrol.
The content to be displayed via TextView is set to appear in bold, 15dip text. To read the content
from the file, info.txt is placed in the assets folder and is displayed via the TextViewcontrol.
Listing 4.44. Code in the Java Activity File MainActivity.java
package in.kvsw.assets;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.widget.TextView;
import java.io.InputStream;
import android.content.res.AssetManager;

Page
54
Mobile Application Development Unit-III

import java.io.IOException;
public class MainActivity extends AppCompatActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView fileView=(TextView)findViewById(R.id.file_view);
InputStream input;
AssetManager assetManager = getAssets();
try
{
input = assetManager.open("info.txt");
int fileSize = input.available();
byte[] buffer = new byte[fileSize];
input.read(buffer);
input.close();
String textForm = new String(buffer);
fileView.setText(textForm);
}
catch (IOException e)
{
fileView.setText("Some exception has occurred");
}
}
}
OUTPUT:

Figure 4.26. The content of the file in the assets folder displayed via TextView

Page
55

You might also like