Professional Documents
Culture Documents
UNIT-III
Building Blocks for Android Application Design
Introduction to Layout:
Under Standing the Components of a Screen
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
C.B.I.T-C.S.E Page 1
Unit-III
<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
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
C.B.I.T-C.S.E Page 3
Unit-III
android:layout_height="match_parent"
android:weightSum="5"
android:orientation="horizontal">
<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
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.
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:
➤➤ 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.
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
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;
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
<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.
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:
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
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.
<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-->
</TableRow></TableLayout>
TableLayout Attributes
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.
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:
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
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
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.
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
android:text=”Middle Button”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true”
/>
</RelativeLayout
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>
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;
{
if(tb.isChecked())
{
resp.setText(“Stop button is displaying”);
}
else
{
resp.setText(“Play button is displaying”)
}
}
});
}}
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;
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
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) <VideoView> tag- used for creating video player view. We need to write this is Xml
Program.
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;
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”.
<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>
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
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