UNIT-III
UNIT-III
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
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
LINEAR LAYOUT
Page 1
Mobile Application Development Unit-III
LinearLayout Attributes
Following are the important attributes specific to LinearLayout −
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
RELATIVE LAYOUT
RelativeLayout Attributes
Following are the important attributes specific to RelativeLayout −
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
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.
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
ABSOLUTE LAYOUT
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.
Public Constructors
AbsoluteLayout(Context context)
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
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.
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
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 −
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 −
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
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
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
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
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
Page
24
Mobile Application Development Unit-III
Value Description
unspecified It is the default value. In such case, system chooses the orientation.
Page
25
Mobile Application Development Unit-III
• 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
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
Page
28
Mobile Application Development Unit-III
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
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
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
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
<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:
<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 setLooping(boolean looping) sets the player for looping or non-
looping.
public void selectTrack(int index) it selects a track for the specified index.
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 setVideoURI (Uri uri) sets the URI of the video file.
Page
46
Mobile Application Development Unit-III
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
Figure 4.24. (left) Horizontal style ProgressBar, (middle) small style ProgressBar, and (right)
large style ProgressBar
Page
49
Mobile Application Development Unit-III
Page
50
Mobile Application Development Unit-III
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