0% found this document useful (0 votes)
11 views84 pages

III B.tech II Sem Mad Unit-3 Lecture Notes

Uploaded by

Vits21 3504
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)
11 views84 pages

III B.tech II Sem Mad Unit-3 Lecture Notes

Uploaded by

Vits21 3504
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/ 84

III.

BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

UNIT- III(A)
LAYING OUT CONTROLS IN CONTAINERS
Introduction to Layouts:
 Layouts are basically containers for other items known as Views, which are displayed on screen.
Layouts are defined in the form of XML files that cannot be changed by our code during runtime.
 Below table shows the layout managers provided by the Android SDK.
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 bounds of container
Displays a single view; that is, the next view replaces the previous view
FrameLayout
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

 The containers or layouts listed in above table are also known as ViewGroups as one or more Views
are grouped and arranged in a desired manner through them.

LinearLayout:
 The LinearLayout is the most basic layout, and it arranges its elements sequentially, either
horizontally or vertically.
 To arrange controls within a linear layout, the following attributes are used:
1. android:orientation—Used for arranging the controls in container in horizontal or vertical order
2. android:layout_width—Used for defining the width of a control
3. android:layout_height—Used for defining the height of a control
4. android:padding—Used for increasing the whitespace between the boundaries of the control and
its actual content
5. android:layout_weight—Used for shrinking or expanding the size of the control to consume the
extra space relative to the other controls in the container
6. android:gravity—Used for aligning content within a control
7. android:layout_gravity—Used for aligning the control within the container

1
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
Applying the orientation Attribute:
 The orientation attribute is used to arrange its children either in horizontal or vertical order.
 If the value of the android:orientation attribute is set to vertical, the children in the linear layout are
arranged in a column layout, one below the other.

 Similarly, if the value of the android:orientation attribute is set to horizontal, the controls in the
linear layout are arranged in a row format, side by side.
 The orientation can be modified at runtime through the setOrientation() method. That is, by
supplying the values HORIZONTAL or VERTICAL to the setOrientation() method, we can arrange
the children of the LinearLayout in row or column format, respectively.

Applying the height and width Attributes:


 The default height and width of a control are decided on the basis of the text or content that is
displayed through it.
 To specify a certain height and width to the control, we use the android:layout_width and
android:layout_height attributes.
 We can specify the values for the height and width attributes in the following three ways:
1. By supplying specific dimension values for the control in terms of px (pi, dip/dp, sp, pts, in, and
mm. For example, android:layout_width="20px" attribute sets the width of control to 20 pixels.
2. By providing the value as wrap_content. When it assigned to the control’s height or width, it
resizes the control to expand to fit its contents.
3. By providing the value as match_parent. When it assigned to the control’s height or width, it
forces size of the control to expand to fill up all the available space of the enclosing container.

Applying the padding Attribute:


 The padding attribute is used to increase the whitespace between the boundaries of the control and
its actual content. Through the android:padding attribute, we can set the same amount of padding or
spacing on all four sides of the control.
 Using the android:paddingLeft, android:paddingRight, android:paddingTop, and android:padding-
Bottom attributes, we can specify the individual spacing on the left, right, top, and bottom of the
control. Example android:padding="5dip", sets the spacing on all four sides of the control to 5 pixels

 Create a new Android Project called LinearLayoutApp to see how the controls are laid out in the
LinearLayout. Default content of the layout file activity_linear_layout_app.xml appears as shown
below.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

2
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".LinearLayoutAppActivity" />
</RelativeLayout>

 Let’s apply the LinearLayout and add three Button controls to the layout. Modify the
activity_linear_layout_app.xml to appear as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

 The orientation of LinearLayout is set to vertical, declaring that we want to arrange its child
elements vertically, one below the other.
 The IDs and text assigned to the three Button controls are Apple, Mango, and Banana. The height of
the three controls is set to wrap_content, which accommodate the text.
 the width of the three controls is set to match_parent, so width of the three controls expands to fill
up space of the LinearLayout container.We see output below.
3
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 To see the controls appear horizontally, set orientation attribute of the LinearLayout to horizontal.
We need to set layout_width attribute of the three controls to wrap_content to display all in a row.
 Let’s modify the activity_linear_layout_app.xml to appear as shown below to observe changes in
figure1.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

4
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Applying the weight Attribute:


 The weight attribute affects the size of the control. we use weight to assign the capability to expand
or shrink and consume extra space relative to the other controls in the container.
 The values of the weight attribute range from 0.0 to 1.0, where 1.0 is the highest value.
 suppose a container has two controls and one of them is assigned the weight of 1. here control
assigned the weight of 1 consumes all the empty space in the container and other should be same.
 To make the middle Button control, Mango, take up all the available space of the container and
modify the activity_linear_layout_app.xml file to appear as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.0" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.0" />
</LinearLayout>
 By setting the layout_weight attributes of Apple, Mango, and Banana to 0.0, 1.0, and 0.0, we allow
the Mango button control to take up all the available space of the container, as shown below.
 If we set the value of layout_weight of Banana to 1.0 and mango to 0.0 then banana button to take
up all spacs of container as shown below.
 If we set the value of layout_weight of three control to 1.0 , entire container space will be equally
consumed by three controls as shown below.

5
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 Similarly if we set the weight of Apple, Mango, and Banana to 0.0, 1.0, and 0.5, respectively, we get
the output shown below.

Applying the Gravity Attribute:


 The Gravity attribute is for aligning the content within a control.
 The valid options for android:gravity include left, center, right, top, bottom,center_horizontal,
center_vertical, fill_horizontal, and fill_vertical.
1. center_vertical—Places the object in vertical center of its container, without changing its size
2. fill_vertical—Grows the vertical size of the object, if needed, so it completely fills its container
3. center_horizontal—Place object in horizontal center of its container, without changing its size
4. fill_horizontal—Grows horizontal size of object, if needed, so it completely fills its container
5. center—Places the object in the center of its container in both the vertical and horizontal axis,
without changing its size
 We can also combine two or more values of any attribute using the | operator. For example
android:gravity="center_horizontal|center_vertical"
 For the above xml, we need to add android:gravity attribute and left and right for button controls
mango and banana.

6
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Using the android:layout_gravity Attribute:


 android:gravity is a setting used by the View, the android:layout_gravity is used by the container.
That is, this attribute is used to align the control within the container.
 Add the android:layout_gravity attribute to align the Button controls themselves. To see the impact
of android:layout_gravity attribute, first arrange them vertically.
 Modify activity_linear_layout_app.xml to make Button controls appear vertically as shown below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

 To align the Button controls Mango and Banana to the center and to the right of the LinearLayout
container, add the following statements to activity_linear_layout_app.xml layout file:
android:layout_gravity="center"
and
android:layout_gravity="right"

 Before apply android:gravity attribute, we adjust the width of control to match_parent from
wrap_content as shown below.

7
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 Now we can apply the android:gravity attribute to align the text within the controls. add the
following three attributes to the Button controls Apple, Mango, and Banana:
android:gravity="left"
android:gravity="center"
and
android:gravity="right"

 Add android:layout_weight="1.0" to all three controls results in expanding their height, as shown
below.

 Modify their android:gravity value as shown below ,to assign text in apple and banana text in
center of button.
android:gravity="center_vertical" for the Apple control
android:gravity="center_vertical|right" for the Banana control

8
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

RelativeLayout:
 In RelativeLayout, each child element is laid out in relation to other child elements; i.e, the location
of a child element is specified in terms of the desired distance from the existing children.
Layout Control Attributes:
 The attributes used to set the location of the control relative to a container are
1. android:layout_alignParentTop—Top of control is set to align with the top of the container.
2. android:layout_alignParentBottom—Bottom of control is set to align with bottom of container.
3. android:layout_alignParentLeft—Left side of control is set to align with left side of container.
4. android:layout_alignParentRight—Right side of control is set to align with right side of container.
5. android:layout_centerHorizontal—Control is placed horizontally at the center of the container.
6. android:layout_centerVertical—Control is placed vertically at the center of the container.
7. android:layout_centerInParent—Control is placed horizontally and vertically at center of container.

 The attributes to control the position of a control in relation to other controls are
1. android:layout_above—The control is placed above the referenced control.
2. android:layout_below—The control is placed below the referenced control.
3. android:layout_toLeftOf—The control is placed to the left of the referenced control.
4. android:layout_toRightOf—The control is placed to the right of the referenced control.

 The attributes that control the alignment of a control in relation to other controls are
1. android:layout_alignTop— Top of the control is set to align with top of referenced control.
2. android:layout_alignBottom—Bottom of control is set to align with bottom of referenced control.
3. android:layout_alignLeft—Left side of control is set to align with left side of referenced control.
4. android:layout_alignRight—Right side of control is set to align with right side of referenced
control.
5. android:layout_alignBaseline—The baseline of the two controls will be aligned.

 For spacing, Android defines two attributes: android:layout_margin and android:padding.The


android:layout_margin attribute defines spacing for the container, while android:padding defines the
spacing for the view.
 Attributes that defines spacing between content and controls are
1. android:padding—Defines the spacing of the content on all four sides of the control.
2. android:paddingTop—Defines the spacing between the content and the top of the control.
3. android:paddingBottom—Defines the spacing between the content and the bottom of the control.
4. android:paddingLeft—Defines the spacing between the content and the left side of the control.
5. android:paddingRight—Defines the spacing between the content and the right side of the control.

9
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 attributes that define the spacing between the control and the container:
1. android:layout_margin—Defines the spacing of the control in relation to the controls or the
container on all four sides.
2. android:layout_marginTop—Defines the spacing between the top of the control and the related
control or container.
3. android:layout_marginBottom—Defines the spacing between the bottom of the control and the
related control or container.
4. android:layout_marginRight—Defines the spacing between the right side of the control and the
related control or container.
5. android:layout_marginLeft—Defines the spacing between the left side of the control and the
related control or container.

 Let’s create a new Android project called RelativeLayoutApp. Modify its layout file
activity_relative_layout_app.xml to appear as shown below.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:layout_marginLeft="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="28dip"
android:layout_toRightOf="@id/Apple"
android:layout_marginLeft="15dip"
android:layout_marginRight="10dip"
android:layout_alignParentTop="true" />

10
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="200dip"
android:layout_height="50dip"
android:layout_marginTop="15dip"
android:layout_below="@id/Apple"
android:layout_alignParentLeft="true" />
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:minWidth="100dp"
android:layout_alignParentRight="true"
android:layout_below="@id/Banana" />
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_below="@id/Banana"
android:paddingTop="15dip"
android:paddingLeft="25dip"
android:paddingRight="25dip" />
</RelativeLayout>

 The Apple button control is set to appear at a distance of 15dip from the top and 20dip from the left
side of the RelativeLayout container.
 The width of the Mango button control is set to consume the available horizontal space. The text
Mango appears at a distance of 28dip from all sides of the control. It is right of the Apple control.
The control is set to appear at a distance of 15dip from the control on the left and 10dip from the
right side of the relative layout container. the top of the Button control is set to align with the top of
the container.
 The Banana button control is assigned the width and height of 200dip and 50dip. The control is set
to appear 15dip below the Apple control. The left side of the control is set to align with the left side
of the container.

11
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 The Grapes button control is set to appear below the Banana button control, and its width is set to
expand just enough to accommodate its content. The height of the control is set to take up all
available vertical space. It appears at the center of the vertical height.The minimum width of the
control is set to 100dip. The right side of the control is set to align with the right side of the
container.
 The Kiwi Button control is set to appear below the Banana control. Its width is set to 100dip, and the
height is set to just accommodate its content. The text Kiwi is set to appear at the distance of 15dip,
25dip, and 25dip from the top, left, and right boundary of the control.
 The Default Code in the Activity File RelativeLayoutAppActivity.java is shown below

package com.androidunleashed.relativelayoutapp;
import android.app.Activity;
import android.os.Bundle;
public class RelativeLayoutDemoActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_relative_layout_app);
}
}

12
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 Let’s create simple login form application that asks user to enter User ID and Password. If either the
User ID or Password is left blank, the message The User ID or password is left blank. Please Try
Again is displayed.
 If the correct User ID and Password, in this case, guest, are entered, then a welcome message is
displayed. Otherwise, the message The User ID or password is incorrect. Please Try Again is
displayed.Xml file for login form activity_login_form.xml is shown below.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/sign_msg"
android:text = "Sign In"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:typeface="serif"
android:textSize="25dip"
android:textStyle="bold"
android:padding="10dip"
android:layout_centerHorizontal="true"/>
<TextView
android:id="@+id/user_msg"
android:text = "User ID:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:layout_below="@+id/sign_msg" />
<EditText
android:id="@+id/user_ID"
android:layout_height="wrap_content"
android:layout_width="250dip"
android:layout_below="@+id/sign_msg"
android:layout_toRightOf="@+id/user_msg"
android:singleLine="true" />
<TextView
android:id="@+id/password_msg"

13
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:text = "Password:"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/user_msg"
android:layout_margin="10dip"
android:paddingTop="10dip"/>
<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_width="250dp"
android:singleLine="true"
android:layout_below="@+id/user_ID"
android:layout_toRightOf="@+id/password_msg"
android:password="true" />
<Button
android:id="@+id/login_button"
android:text="Sign In"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dip"
android:layout_below="@+id/password_msg"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"
android:layout_below="@+id/login_button"/>
</RelativeLayout>

 in TextView control sign_msg, the text Sign In is displayed horizontally centered at the top. It is
displayed in bold serif font, 25 dip in size. The text is padded with a space of 10dip on all four sides
of its container.
 TextView control user_msg, displays the text User ID below the TextView sign_msg. The TextView
is placed 10dip from all four sides.
 EditText control user_ID is displayed below sign_msg and to the right of user_msg. The width
assigned to the TextView control is 250 dip and is set to single-line mode, so if the user types
beyond the given width, the text scrolls to accommodate extra text.

14
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 TextView password_msg control displaying the text Password, is displayed below the TextView
user_msg. The TextView control is placed at a spacing of 10dip from all four sides, and the text
Password: is displayed at 10dip from the control’s top.
 EditText control password is displayed below the EditText user_ID and to the right of the TextView
password_msg. The width assigned to the TextView control is 250 dip and is set to single-line
mode. typed characters are converted into dots for security.
 Button control login_button with the caption Sign In is displayed below the TextView
password_msg. The button is horizontally centered and is set to appear at 10dip distance from the
EditText control password.
 A TextView control response is placed below the Button login_button. It is used to display messages
to the user when the Sign In button is pressed after entering UserID and Password.
 We write the code in the activity file LoginFormActivity.java as shown below, to validate UserID
and Password and displays welcome message when user is authorized.

package com.androidunleashed.loginform;
import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
import android.widget.TextView;
public class LoginFormActivity extends Activity implements OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
Button b = (Button)this.findViewById(R.id.login_button);
b.setOnClickListener(this);
}
public void onClick(View v) {
EditText userid = (EditText) findViewById(R.id.user_ID);
EditText password = (EditText) findViewById(R.id.password);
TextView resp = (TextView)this.findViewById(R.id.response);
String usr = userid.getText().toString();
String pswd = password.getText().toString();
if(usr.trim().length() == 0 || pswd.trim().length() == 0){

15
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

String str = "The User ID or password is left blank \nPlease Try Again";
resp.setText(str);
}
else{
if(usr.equals("guest") && pswd.equals("guest")) resp.setText("Welcome " + usr+ " ! ");
else resp.setText("The User ID or password is incorrect \nPlease Try Again");
}
}
}

 The Button control is accessed from the layout file and is mapped to the Button object b. This
activity implements the OnClickListener interface.
 Hence, the class implements the callback method onClick(), which is invoked when a click event
occurs on the Button control.
 In the onClick() method, the user_ID and password EditText controls are accessed from the layout
file and mapped to the EditText objects userid and password. TextView control response is accessed
from layout file and is mapped to the TextView object resp.
 User ID and password accessed through the objects userid and password and assigned to the two
Strings usr and pswd. These are checked for authentication.
 If the user has left any of the EditText controls blank, the message The User ID or password is left
blank. Please Try Again is displayed.
 If the User ID and password are correct, then a welcome message is displayed. Otherwise, the
message The User ID or password is incorrect. PleaseTry Again is displayed.

16
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

AbsoluteLayout:
 Each child in an AbsoluteLayout is given a specific location within the bounds of the container.
Such fixed locations make AbsoluteLayout incompatible with devices of different screen size and
resolution.
 The controls in AbsoluteLayout are laid out by specifying their exact X and Y positions. The
coordinate 0, 0 is the origin and is located at the top-left corner of the screen.
 Create a new Android Project called AbsoluteLayoutApp. Modify its layout file,
activity_absolute_layout_app.xml, as shown below.

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Product Form"
android:textSize="20sp"
android.textStyle="bold"
android:layout_x="90dip"
android:layout_y="2dip"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Code:"
android:layout_x="5dip"
android:layout_y="40dip" />
<EditText
android:id="@+id/product_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="100dip"
android:layout_x="110dip"
android:layout_y="30dip" />
<TextView
android:layout_width="wrap_content"

17
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:layout_height="wrap_content"
android:text="Product Name:"
android:layout_x="5dip"
android:layout_y="90dip"/>
<EditText
android:id="@+id/product_name"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:minWidth="200dip"
android:layout_x="110dip"
android:layout_y="80dip"
android:scrollHorizontally="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product Price:"
android:layout_x="5dip"
android:layout_y="140dip" />
<EditText
android:id="@+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="100dip"
android:layout_x="110dip"
android:layout_y="130dip" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Add New Product"
android:layout_x="80dip"
android:layout_y="190dip" />
</AbsoluteLayout>

 The New Product Form TextView is set to appear 90dip from the left and 2dip from the top side of
the container. The size of the text is set to 20sp, and its style is set to bold.
 The Product Code TextView is set to appear 5dip from left and 40dip from top side of the container.

18
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 The product_code EditText control is set to appear 110dip from the left and 30dip from the top side
of the container. The minimum width of the control is set to 100dp.
 ProductName TextView control is set to appear 5dip from left and 90dip from top side of container.
 The product_name EditText control is set to appear 110dip from the left and 80dip from the top side
of the container. The minimum width of the control is set to 200dip, and its text is set to scroll
horizontally
 The Product Price TextView is set to appear 5dip from left and 140dip from top side of container.
 The product_price EditText control is set to appear 110dip from the left and 130dip from the top
side of the container. The minimum width of the control is set to 100dip.
 The click_btn Button, Add New Product, is set to appear 80dip from the left and 190dip from the top
side of the container.
 If we don’t specify the x, y coordinates of a control in AbsoluteLayout, it is placed in the origin
point, that is, at location 0, 0. The values of the x and y coordinates are specified in any units, such
as sp, in, mm, and pt.
 After specifying the locations of controls in the layout file activity_absolute_layout_app.xml, we can
run the application. There is no need to make any changes in the file
AbsoluteLayoutAppActivity.java. After application is run, we get the output shown below.

Using ImageView:
 An ImageView control is used to display images in Android applications. An image can be
displayed by assigning it to the ImageView control and including the android:src attribute in XML
definition . Images can also be dynamically assigned to the ImageView control through Java code.

19
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 A sample ImageView tag when used in the layout file is shown here:
<ImageView
android:id="@+id/first_image"
android:src = "@drawable/bintupic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:maxHeight="100dip"
android:maxWidth="250dip"
android:minHeight="100dip"
android:minWidth="250dip"
android:resizeMode="horizontal|vertical" />

 Some of attributes not familiar with you are shown below


1. android:src—Used to assign the image from drawable resources. image in the res/drawable
folder is set to display through the ImageView control via this attribute.
Example: android:src = "@drawable/bintupic"
NOTE: You do not need to specify the image file extension. JPG and GIF files are supported,
but the preferred image format is PNG.
2. android:scaleType—Used to scale an image to fit its container. The valid values fornthis
attribute include fitXY, center, centerInside, and fitCenter.
a. The value fitXY independently scales the image around the X and Y axes without
maintaining the aspect ratio to match the size of container.
b. The value center centers the image in the container without scaling it.
c. The value centerInside scales the image uniformly, maintaining the aspect ratio so that the
width and height of the image fit the size of its container.
d. The value fitCenter scales the image while maintaining the aspect ratio, so that one of its X
or Y axes fits the container.
3. android:adjustViewBounds—If set to true, the attribute adjusts the bounds of the ImageView
control to maintain the aspect ratio of the image displayed through it.
4. android:resizeMode—The resizeMode attribute is used to make a control resizable so we can
resize it horizontally, vertically, or around both axes. We need to click and hold the control to
display its resize handles. The resize handles can be dragged in the desired direction to resize the
control. The available values for the resizeMode attribute include horizontal, vertical, and none.

20
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

FrameLayout:
 FrameLayout is used to display a single View. The View added to a FrameLayout is placed at
the top-left edge of the layout. Any other View added to the FrameLayout overlaps the
previous View; that is, each View stacks on top of the previous one.
 In FrameLayout, we will place two ImageView controls in the
FrameLayout container. only one ImageView will be visible and other
will overlap with existing one.
 We will also display a button on the ImageView, which, when selected,
displays the hidden ImageView underneath.
 To display images in Android applications, the image is first copied
into the res/drawable folder and from there, it is referred to in the layout
and other XML files.
 There are four types of drawable folders: drawable-xhdpi,drawable-
hdpi, /res/drawable-mdpi, and /res/drawable-ldpi. We have to place
images of different resolutions and sizes in these folders.
 if we copy two images called bintupic.png and bintupic2.png of the
preceding size and resolution and paste them into the four res/drawable
folders.
 To display two ImageViews and a TextView in the application, let’s
write the code in the layout file activity_frame_layout_app.xml as
shown below

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/first_image"
android:src = "@drawable/bintupic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
<ImageView
android:id="@+id/second_image"
android:src = "@drawable/bintupic2"
android:layout_width="match_parent"

21
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:layout_height="match_parent"
android:scaleType="fitXY" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click the image to switch"
android:layout_gravity="center_horizontal|bottom"
android:padding="5dip"
android:textColor="#ffffff"
android:textStyle="bold"
android:background="#333333"
android:layout_marginBottom="10dip" />
</FrameLayout>

 The first_image and second_image ImageView controls are set to display the images bintupic.png
and bintupic2.png. To make the two images stretch to cover the entire screen, the scaleType attribute
is set to fitXY.
 A TextView, Click the image to switch, is set to display at the horizontally centered position and at a
distance of 10dip from the bottom of the container.
 The spacing between the text and the boundary of the TextView control is set to 5dip. The
background of the text is set to a dark color, the foreground color is set to white.
 When a user selects the current image on the screen, the image should switch to show the hidden
image. To show the activity, we need to write code in the activity file as shown below.
package com.androidunleashed.framelayoutapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.view.View.OnClickListener;
import android.view.View;
public class FrameLayoutAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frame_layout_app);
final ImageView first_image = (ImageView)this.findViewById(R.id.first_image);
final ImageView second_image = (ImageView)this.findViewById(R.id.second_image);
first_image.setOnClickListener(new OnClickListener(){

22
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

public void onClick(View view) {


second_image.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
}
});
second_image.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
first_image.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
}
});
}
}
 The two first_image and second_image ImageView controls are located through the findViewById
method of the Activity class and assigned to the two ImageView objects,first_image and
second_image.
 We register the click event by calling the setOnClickListener() with onClick() method.by onClick()
we switch the images; that is, we make the current ImageView invisible and the hidden ImageView
visible. When the application runs, we see the output shown below.

TableLayout:
 The TableLayout is used for arranging the enclosed controls into rows and columns. Each new row
defined through a TableRow object. A row can have zero or more controls, where each control is
called a cell.
 The number of columns in a TableLayout is determined by the maximum number of cells in any
row. The width of a column is equal to the widest cell in that column.

23
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 Operations Applicable to TableLayout


1. Stretching Columns:
 The default width of a column is set equal to the width of the widest column, but we can
stretch the column(s) to take up available free space using the android:stretchColumns
attribute in the TableLayout.
 The value assigned to this attribute can be a single column number or a comma-delimited list
of column numbers. Specified columns arestretched to take up any available space on row.
Examples:
1. android:stretchColumns="1"—The second column is stretched to take up any available
space in the row.
2. android:stretchColumns="0,1"—Both the first and second columns are stretched to take up
the available space in the row.
3. android:stretchColumns="*"—All columns are stretched to take up available space in row.

2. Shrinking Columns:
 We can shrink or reduce the width of the column(s) using the android:shrinkColumns
attribute in the TableLayout.
 We can specify either a single column or a comma-delimited list of column numbers for this
attribute. The content in the specified columns word wraps to reduce their width.
Examples:
1. android:shrinkColumns="0"—The first column’s width shrinks or reduces by word
wrapping its content.
2. android:shrinkColumns="*"—The content of all columns is word-wrapped to shrink their
widths.

3. Collapsing Columns:
 We can make the column(s) collapse or become invisible through the
android:collapseColumns attribute in the TableLayout. We can specify one or more comma-
delimited columns for this attribute.
 These columns are part of the table information but are invisible. We can also make
column(s) visible and invisible through coding by passing theBoolean values false and true,
to the setColumnCollapsed() method.
Example:
android:collapseColumns="0"—The first column appears collapsed; that is, it is part of the table
but is invisible. It can be made visible through coding by using setColumnCollapsed() method.

24
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

4. Spanning Columns:
 We can make a column span or take up the space of one or more columns by using the
android:layout_span attribute.
 The value assigned to this attribute must be >=1. For example, the following value makes the
control take or span up to two columns. Example, android:layout_span="2"

 Create a new Android project called TableLayoutApp. Make its layout file activity_table_layout
_app.xml appear as shown below.

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1">
<TableRow android:padding="5dip">
<TextView
android:layout_height="wrap_content"
android:text="New Product Form"
android:typeface="serif"
android:layout_span="2"
android:gravity="center_horizontal"
android:textSize="20dip" />
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:text="Product Code:"
android:layout_column="0"/>
<EditText
android:id="@+id/prod_code"
android:layout_height="wrap_content"
android:layout_column="1"/>
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"

25
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:text="Product Name:"
android:layout_column="0"/>
<EditText
android:id="@+id/prod_name"
android:layout_height="wrap_content"
android:scrollHorizontally="true" />
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:text="Product Price:" />
<EditText
android:id="@+id/prod_price"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<Button
android:id="@+id/add_button"
android:text="Add Product"
android:layout_height="wrap_content" />
<Button
android:id="@+id/cancel_button"
android:text="Cancel"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>

 In TableLayout, as their width will be always set to match_parent and layout_height attribute of the
TableRow is always wrap_content. Cells are added to a row in increasing column order. If we don’t
specify a column number for any cell, it is considered to be the next available column.
 If we skip a column number, it is considered an empty cell in that row. We can use any View
subclass as a direct child of TableLayout. The View is displayed as a single row that spans all the
table columns.
 The first row of the table has a single control, New Product Form TextView. The TextView is set to
span two columns and is set to appear at the center of the horizontal space. The font is set to serif,
20dip in size.

26
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 In the second row, a TextView and an EditText control are displayed. The TextView control with
text Product Code is set to appear at the column 0 location and the EditText control is set to appear
at column 1.
 In the third row, again two controls, TextView and EditText, are displayed. The TextView control
with the text Product Name is set to appear in column 0. If the user types text beyond the width of
the EditText control, the content scrolls horizontally.
 In the fourth row, the TextView control with the text Product Price is displayed in the first column,
and the EditText control is displayed in the second column.
 In the fifth row, a Button control with the caption Add Product is displayed in the first column, and
a Button control with the caption Cancel is displayed in the second column.

GridLayout Layout:
 GridLayout lays out views in a two-dimensional grid pattern, that is, in a series of rows and
columns. The intersection of row and column is known as a grid cell, and it is the place where child
views are placed.
 Without specifying intermediate views, we can flexibly place the views randomly in the grid by
specifying their row and column positions. More than one view can be placed in a grid cell.
1. Specifying Row and Column Position
 The two attributes that are used to specify the row and column position of the grid cell for
inserting views are android:layout_row and android:layout_column. Together, they specify
the exact location of the grid cell for placing the view.
 For example, following statements place the view at first row and column position of grid:
android:layout_row="0"
android:layout_column="0"

27
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

2. Spanning Rows and Columns


 Views can span rows or columns if desired. The attributes are android:layout_rowSpan and
android:layout_columnSpan.
 For example, android:layout_rowSpan="2"
android:layout_columnSpan="3"

3. Inserting Spaces in the GridLayout


 For inserting spaces, a spacing view called Space is used. That is, to insert spaces, the Space
view is inserted as a child view.
 For example, <Space android:layout_row="3"
android:layout_column="0"
android:layout_columnSpan="3"
android:layout_gravity="fill" />

 Let’s create a new Android project called GridLayoutLayoutApp. Make its layout file,
activity_grid_layout_app.xml, appear as shown below.

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:rowCount="7"
android:columnCount="2" >
<TextView
android:layout_row="0"
android:layout_column="0"
android:text="New Product Form"
android:typeface="serif"
android:layout_columnSpan="2"
android:layout_gravity="center_horizontal"
android:textSize="20dip" />
<Space
android:layout_row="1"
android:layout_column="0"
android:layout_width="50dp"
android:layout_height="10dp" />

28
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

<TextView
android:layout_row="2"
android:layout_column="0"
android:text="Product Code:" />
<EditText
android:id="@+id/prod_code"
android:layout_width="100dip" />
<TextView
android:text="Product Name:" />
<EditText
android:layout_row="3"
android:layout_column="1"
android:id="@+id/prod_name"
android:layout_width="200dip" />
<TextView
android:layout_row="4"
android:layout_column="0"
android:text="Product Price:" />
<EditText
android:layout_row="4"
android:layout_column="1"
android:id="@+id/prod_price"
android:layout_width="100dip" />
<Space
android:layout_row="5"
android:layout_column="0"
android:layout_width="50dp"
android:layout_height="20dp" />
<Button
android:layout_row="6"
android:layout_column="0"
android:id="@+id/add_button"
android:text="Add Product" />
<Button
android:id="@+id/cancel_button"
android:text="Cancel" />
</GridLayout>

29
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 In the preceding code, the GridLayout is defined as consisting of seven rows and two columns. The
orientation of GridLayout is set to horizontal; that is, controls are placed in rows.
 A TextView with the text New Product Form is set to appear at the first row and column position of
the grid. The text appears in serif font and in 20dip size. The text spans two columns and appears at
the center of the row.
 A blank space is inserted at the second row and first column position. The width and height of the
blank space are 50dp and 10dp.
 A TextView with text Product Code: is set to appear at third row and first column position of grid.
 An EditText control with the ID prod_code of width 100dip is set to appear at the third row and
second column position of the grid.
 TextView with text Product Name: is set to appear at fourth row and first column position of grid.
 An EditText control with the ID prod_name of width 200dip is set to appear at the fourth row and
second column of the grid.
 A TextView with the text Product Price: is set to appear at the fifth row and first column of the grid.
 An EditText control with the ID prod_price of width 100dip is set to appear at the fifth row and
second column position of the grid
 A blank space is inserted at the sixth row and first column position. The width and height of the
blank space are 50dp and 20dp.
 A Button control with the caption "Add Product" is set to appear at the seventh row and first column
of the grid. Button control with the caption "Cancel" is set to appear at the seventh row and second
column of the grid.
 There is no need to write any code in the Java activity file GridLayoutAppActivity.java. When the
application is run, the controls are laid out in the grid pattern as shown below.

30
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Adapting to Screen Orientation:


 Android supports two screen orientations: portrait and landscape. When the screen orientation of
device is changed, the current activity being displayed is destroyed and recreated automatically to
redraw its content in the new orientation.
 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.
 Controls need to be laid out differently in the two screen orientations because of the difference in the
height and width of the two orientations.
 There are two ways to handle changes in screen orientation:
1. 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.
2. Defining layout for each mode—A new layout file is defined for each of the two screen
orientations, One for Portrait mode, and the other for Landscape mode.

Anchoring Controls:
 For anchoring controls relative to the four edges of the screen, we use a RelativeLayout container.
Let’s creating an Android project called ScreenOrientationApp. Write the code in the layout file
activity_screen_orientation_app.xml as shown below.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:layout_marginLeft="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="match_parent"

31
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:layout_height="wrap_content"
android:padding="28dip"
android:layout_toRightOf="@id/Apple"
android:layout_marginLeft="15dip"
android:layout_marginRight="10dip"
android:layout_alignParentTop="true" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="200dip"
android:layout_height="50dip"
android:layout_marginTop="15dip"
android:layout_below="@id/Apple"
android:layout_alignParentLeft="true" />
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:minWidth="100dp"
android:layout_alignParentRight="true"
android:layout_below="@id/Banana" />
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_below="@id/Banana"
android:paddingTop="15dip"
android:paddingLeft="25dip"
android:paddingRight="25dip" />
</RelativeLayout>

 The controls are aligned relative to the edges of the container or in relation to each other. keep the
activity file ScreenOrientationAppActivity.java unchanged with the default code

32
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

package com.androidunleashed.screenorientationapp;
import android.app.Activity;
import android.os.Bundle;
public class ScreenOrientationAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_orientation_app);
}
}
 When the application is run while in the default portrait mode, the controls appear as shown below.
Because the five Button controls are placed in relation to the four edges of the container and in
relation to each other.
 If the screen is rotated to landscape mode, controls not disappear due to four edges of container.

Defining Layout for Each Mode:


 We define two layouts. One for portrait and other for landscape mode. To understand this, write
code in activity_screen_orientation_app.xml for laying controls for portrait mode.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

33
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="300dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
</LinearLayout>

34
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 If we run the application without defining the layout for the landscape mode, we find that last two
controls disappeared when screen orientation to landscape.

 To use the blank space on the right side of the screen in landscape mode, we need to define another
layout file, activity_screen_orientation_app.xml, in the res/layout-land folder.
 The layout-land folder has to be created manually inside the res folder then Copy the
activity_screen_orientation_app.xml file from the res/layout folder and paste it into res/layout-land
folder. Modify the activity_screen_orientation_app.xml file as shown below.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"
android:layout_width="250dp"
android:layout_height="wrap_content"
35
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_toRightOf="@id/Apple" />
<Button
android:id="@+id/Banana"
android:text="Banana"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_below="@id/Apple" />
<Button
android:id="@+id/Grapes"
android:text="Grapes"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_below="@id/Apple"
android:layout_toRightOf="@id/Banana" />
<Button
android:id="@+id/Kiwi"
android:text="Kiwi"
android:layout_width="250dip"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip"
android:layout_below="@id/Banana" />
</RelativeLayout>

 To fill up the blank space on the right side of the screen, the Mango and Grapes button controls are
set to appear to the right of the Apple and Banana button controls.
 We can also detect the screen orientation via Java code. Modify the activity file ScreenOrientation-
AppActivity.java to display a toast message when the screen switches between landscape mode and
portrait mode.

36
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

package com.androidunleashed.screenorientationapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class ScreenOrientationAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_orientation_app);
if(getResources().getDisplayMetrics().widthPixels>getResources().getDisplayMetrics().heightPi
xels)
{
Toast.makeText(this,"Screen switched to Landscape mode",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this,"Screen switched to Portrait mode",Toast.LENGTH_SHORT).show();
}
}
}
 when we run the application, the controls appear in portrait mode and landscape mode as shown
below

37
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

UNIT- III(B)
UTILIZING RESOURCES AND MEDIA
Resources:
 Resources in android refer to external files that hold information such as strings, images, layouts and
audio supplied to application. We can maintain and modify external files without disturbing code.
Example changing string content in resource file is easier than changes to hard-coded strings.
 Resources are stored in res folder of our project. Resources are broadly divided into three categories.
Those are values, drawables and layouts.AWD wizard automatically creates res folder that contains
sub-folders for values, drawables and layout resources.

Types of Resources:
1. Drawable folder:
 Depending on the target platform chosen our application can have 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.
 Android chooses the images from the respective directory depending on the density of the device
used to run the application.

2. Layout folder:
 This folder contains a layout file automatically created for us. The default name assigned to the
file is activity_main.xml, but we can assign any name to it.

3. Menu folder:
 This folder contains xml files that represent application menus. Default name assigned to menu
file that is automatically created is activity_main.xml, but we can change name if we want.

4. Values folder:
 This folder by default contains a strings.xml files that we can use to define values resources that
includes strings, colors, dimensions, styles and string or integer arrays.
 The following is a list of some xml files that we can create in the values folder:
1. Arrays.xml—for defining arrays resources
2. Colors.xml—for defining color resources that define color values
3. Dimens.xml—for defining dimension resources to standardize certain application
measurements
4. Strings.xml—for defining string resources
5. Styles.xml—for defining styles resources to format or change the appearance of our views
and application

1
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
5. Values-v11:
 The folder contains the styles.xml file that declares the holographic them which is used when the
application runs on android 3.0(API level 11) or higher.
6. Values-v14:
 The folder contains the styles.xml file that declares the device default themes which is used
when the application runs on android 4.0(API level 14) or higher.
 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.

Creating values resources:


 All the values in resources 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 mostly string resources file is named strings.xml. The resources
filenames should contain only lowercase letters, numbers, period(.) and underscore(_) symbols.
 The strings.xml file that is automatically created for us by the ADT wizard contains the default
content is shown below.
<resources>
<string name="app_name">ValuesResourcesApp</string>
<string name="hello_world">Hello World! </string>
<string name="menu_settings">Settings</string>
<string name="title_activity_values_resources_app">ValuesResourcesAppActivity</string>
</resources>
 Modify above strings.xml file as shown below to get much awareness about resources
<resources>
<string name="app_name">ValuesResourcesApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_values_resources_app">ValuesResourcesAppActivity</string>
<string name="str_name">XYZ Restaurant</string>
<string name="str_address">11, Hill View Street, New York</string>
<string name="str_message"><b>Welcome</b></string>
</resources>
 We can see that the string resources file has a root element, <resources> followed by one or more
child elements <string>.
 Each string resource contains name property used to assign unique resource ID to string. Example,
app_name, str_name, str_address and str_message are the resource IDs of the respective strings are
used in other resources files or java code for accessing the respective string resources.

2
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 we can use the string resources of the preceding xml file in other resources files by using the
following syntax: @string/resource_ID
For examples to access the string resources with the resource ID str_addresss in another resources
file we use the following code: @string/str_address
 All string resource files will be complied and placed in R.java file. In the java code we can access
the resources using the following syntax: R.string.resource_ID
For examples to access the string resource with the resource ID str _address in the java code we use
the following statement: R.string.str_name
 We use the getString() method to access string resource in java code. statement to access the string
resource with the resource ID str_address is getString(R.string.str_address);
 To access the string resources defined in the file strings.xml, create and modify layout file
activity_values_resources_app.xml shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message" />
</LinearLayout>
 The statement android:text=”@string/str_name” accesses a string resource from a resource file
res/values/string.xml, whose name property is str_name. The text in the string resource str_name is
assigned to the TextView for display.
 Similarly, string resource str_message is accessed and assigned toTextView message_view. Hence,
text XYZ Restaurant and welcome message appear on the screen through first and third TextView
controls, name_view and message_view.

3
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 In middle TextView, string resource address_view is accessed and assigned to TextView through
Java code. Modify ValuesResourcesAppActivity.java file as shown below.
package com.androidunleashed.valuesresourcesapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ValuesResourcesAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_values_resources_app);
String strAddress=getString(R.string.str_address);
TextView addressView=(TextView)findViewById(R.id.address_view);
addressView.setText(strAddress);
}
}
 The string resource with the resource ID str_address is accessed and assigned to the String object
strAddress. The content of the string resource that is saved in the strAddress object assigned to the
TextView object address_view to display on screen.

Dimension Resources:
 Dimension resources are used to specify the sizes for fonts, layouts, and widgets. We can modify the
size of any control in the application without changing the code. We can define dimensions for
different screen resolutions and densities to support different hardware.
 To try it, open application ValuesResourcesApp and add an XML file called dimens.xml then add
the code as shown in below

4
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

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


<resources>
<dimen name="small_size">15dp</dimen>
<dimen name="medium_size">15sp</dimen>
<dimen name="large_size">20pt</dimen>
</resources>
 We see that dimension resources are defined through dimen element. It contains a numerical value
followed by unit of measurement (px, in, mm, pt, dp and sp).
 In the dimen.xml file, we have defined three dimension resources:15dp, 15sp, and 20pt represented
by the three resources IDs small_size, medium_size, and large_size.
 To apply dimension resource to our TextView controls modify activity_values_resources_app.xml
as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"
android:textSize="@dimen/small_size" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message"
android:textSize="@dimen/large_size" />
</LinearLayout>
 two statements, android:textSize=”@dimen/small_size”
and
android:textSize=”@dimen/large_size” are used to apply text size 15px and 20sp
to two TextViews with the IDs name_view and message_view.

5
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 To apply dimension resources medium_size to our TextView address_view, add these statements to
the Java file Values ResourcesAppActivity.java:
float addressSize= this.getResources().getDimension(R.dimen.medium_size);
addressView.setTextSize(addressSize);
 We access our Resources object by calling the getResources() method Then, through the Resources
object, we access the dimension by supplying its resource ID to the getDimension() method.
 Dimension accessed is then applied to TextView using the setTextsize() method. After application is
run, we find that the three TextView controls with sizes defined in the dimension resources.

Color Resources:
 To define a color resource, we use the color element. The color value is specified in the form of
hexadecimal RGB values preceded by an optional Alpha channel.
 We can specify the color either through single character hex values or double character hex values
formats, as shown here:
 #RGB –for example, #F00 for a red color.
 #RRGGBBB-for example, #FF0000 for a red color.
 #ARGB-for example, #5F00 for a red color with an Alpha of 5.
 #AARRGGBB-for example, #50FF0000 for a red color with an Alpha of 50.
 To apply color resources to our application ValuesResourceApp, add an XML file called colors.xml
to the values folder then write below code in it:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red_color">#F00</color>
<color name="green_color">#00FF00</color>
<color name="blue_alpha_color">#500000FF</color>
</resources>

6
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 This code defines three color resources that present the three colors red, green, and blue through the
resource Ids red_color, green_color and blue_alpha_color. To apply color resources to TextView
modify layout file activity_values_resources_app.xml as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match parent"
android:layout_height="match parent">
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"
android:textSize="@dimen/small_size"
android:textColor="@color/red_color"/>
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message"
android:textSize="@dimen/large_size"
android:textColor="@color/blue_alpha_color"/>
</LinearLayout>
 two statements, android:textColor=”@color/red_color”
and
android:textColor=”@color/blue_alpha_color” are used to apply colors to text of
two TextViews of IDs name_view and message_view.
 To apply the color resource to the TextView address_view, we use Java code. Add the following
lines of code to the Java file ValuesResourcesAppActivity.java:
int addressColor=this.getResources().getColor(R.color.green_color);
addressView.setTextColor(addressColor);
 Resource object is accessed by calling the getResources() method then we can access the color
resource by supplying its resource ID to getcolor() method.

7
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 The color accessed is then applied to the address View TextView by using the setTextColor()
method. To get desired output modify code in ValuesResourcesAppActivity.java is shown below.
package.com.androidunleashed.valuesresourceapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ValuesResourcesAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_values_resources_app);
String strAddress=getString(R.string.str_address);
TextView addressView=(TextView)findViewById(R.id.address_view);
addressView.setText(strAddress);
int addressColor=this.getResources().getColor(R.color.green_color);
addressView.setTextColor(addressColor);
float addressSize= this.getResources().getDimension(R.dimen.medium_size);
addressView.setTextSize(addressSize);
}
}
 When the application is run, we see the three TextView controls appearing with colors defined in the
color resources.

Styles and Themes:


 A style is a collection of attributes such as color, font, margin, and padding that we can apply
collectively to our Views, Activity, or an entire application.

8
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 We can easily change appearance of our views and application by simply specifying different style
or modify existing style without disturbing java code.
 A style is created by using a style element with one or more item child elements. The style element
includes a name property to specify the resource ID. Each item element includes a name property to
define the attributes such as color, font, and so on.
<resources>
<style name="resource_ID">
<item name="attribute_name">value</item>
</resources>
 Styles support inheritance; that is, the attribute of any existing style can be accessed and included in
the current style by using parent property of the style element. For example,
<style name=”style2” parent =”style1”>
 To apply styles to the individual views in the layout file, open the styles.xml file that already exists
in the values folder then modify it as shown below.
<resources>
<style name="AppTheme" parent="android:Theme.Light"/>
<style name="style1">
<item name="android:textColor">#0000FF</item>
<item name="android:typeface">serif</item>
<item name="android:textSize">30sp</item>
</style>
<style name="style2" parent="style1">
<item name="android:textColor">#0000FF</item>
<item name="android:typeface">sans</item>
<item name="android:background">#FF0000</item>
<item name="android:padding">10dip</item>
</style>
<style name="style3" parent="style2">
<item name="android:textColor">#00FF00</item>
<item name="android:background">#000000</item>
<item name="android:typeface">monospace</item>
<item name="android:gravity">center</item>
</style>
</resources>
 We can see that three styles are defined with IDS: style1, style2, and style3. In style1, we defines
text color to green, font to sarif and font size to 30sp.

9
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 style2 inherits style1; hence it automatically gets preceding three attributes. style2 overrides font to
sans and text color to blue.style2 defines background color of text to red and padding to 10dip.
 style3 inherits style2; hence it automatically gets preceding five attributes. It overrides attributes text
color to green, background color to black, and font to monospace. style3 define gravity to center
 To apply three styles to the three TextView controls. Modify activity_values_resources_app.xml as
shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"
style="@style/style1" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/style2"
android:text="@string/str_address"/>
/>
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/style3"
android:text="@string/str_message" />
</LinearLayout>
 We see that style2, style2, and style3 are applied to the three TextViews controls name_view,
address_view, and message_view. The content first TextView appears in green, serif font and 30sp
in size.
 Similarly, the content of the second TextView appears in blue foreground color, red background
color, serif font, 30sp in size and 10 dip padding on all sides of TextView.
 The content in the third TextView appears in monospace font, green foreground color, black
background, 30sp in size and the text appears at the center of the TextView.

10
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 We don’t need any code in the activity file. So remove all the code that we have been adding to it.
Modify valuesResourceAppActivity.java as shown below.
com.androidunleashed.valueresourceapp;
import android.app.Activity;
import android.os.Bundle;
public class ValuesResourcesAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_values_resources_app);
}
}

Applying Themes:
 We can apply the style element to entire activity or application by adding the android:theme attribute
to the android manifest. If we add the android:theme attribute to <activity> element in the android
manifest, all attributes of the style are applied to every view within Activity.
 If we add the android:theme attribute to <application> element in the android manifest, all the
attributes of the style are applied to activities in the application. The android manifest.Xml file of
our application ValuesResourceApp originally appears as shown below.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
Package="com.androidunleashed.valuesresourceapp"
android:versioncode="1"
android:versionName="1.0">
<use-sdk
android:minsdkversion="8"
android:targetsdkversion="15"/>

11
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

<application
android:icon="@drawable/ic_launcher"
android:lable="@string/app_nanme"
android:theme="@style/appTheme">
<activity
android:name=".ValueresourceappActivity"
android:label="@string/title-activity_value_resources-app">
<intent-filter>
<action android:name="android.intent.catagery.MAIN"/>
<category android:name="android.intent.catagery.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
 Let’s apply style3 in styles.xml to the entire application by modifying the android:theme attribute in
AndroidManifest.xml file, as shown below.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
Package="com.androidunleashed.valuesresourceapp"
android:versioncode="1"
android:versionName="1.0">
<use-sdk
android:minsdkversion="8"
android:targetsdkversion="15"/>
<application
android:icon="@drawable/ic_launcher"
android:lable="@string/app_nanme"
android:theme="@style/style3">
<activity
android:name=".ValueresourceappActivity"
android:label="@string/title-activity_value_resources-app">
<intent-filter>
<action android:name="android.intent.catagery.MAIN"/>
<category android:name="android.intent.catagery.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

12
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 To see the impact of applying the style to the entire application, we need to remove the styles in the
layout file and modify activity_values_resources_app.xml to appear as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"/>
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_address"/>
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message"/>
</LinearLayout>
 After the application is run, all three views appears in monospace font, green foreground color,
black background color , 30sp in size and text appears at the center of container as shown below.

13
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Arrays:
 Arrays refer to a collection of values or elements. Any element in an array can be referenced directly
by specifying its index/subscription value. Arrays can be in the form of strings or integers and are
used for storing the data of their respective data type.

Using String Arrays:


 String array provides an array of strings. Such a resource is popularly used with selection widgets
such as ListView and Spinner that need to display a collection of selectable items to user.
 To define a string array, we use the following syntax:
<string-array name=”array_name”>
<item>text1</item>
<item>text2</item>
.......
.......
</string-array>
 The name property acts as the resource ID and text1, text2, and so on represent the elements of the
string. The syntax for defining an integer array is shown here:
<integer-array name=”array_name”>
<item>number1</item>
<item>number2</item>
.....
.....
</integer-array>
 To understand string-array, create a new android project called StringArrayApp. In strings resource
file strings.xml, define a string-array called fruits and assign a few strings to it as shown below.
<resources>
<string name="app_name">StringArrayApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_string_array_app">StringArrayAppActivity</string>
<string-array name="fruits">
<item>Apple</item>
<item>Mango</item>
<item>Orange</item>
<item>Grapes</item>
<item>Banana</item>
</string-array>
</resources>

14
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 We see that string array fruits consist of five string elements, namely Apple, Mango, Orange,
Grapes, and Banana. To make these string elements appear in a TextView. Add a TextView to the
layout file. The code appears as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fruits_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
 To access the elements of the string array and to display them via the TextView, we write the code
in StringArrayAppActivity.java as shown below.
package com.androidunleashed.stringarrayapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class StringArrayAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_string_array_app);
TextView fruitsView=(TextView)findViewById(R.id.fruits_view);
String[] fruitsArray=getResources().getStringArray(R.array.fruits);
String str="";
for( int i=0;i<fruitsArray.length;i++) {
str+=fruitsArray[i] +"\n";
}
fruitsView.setText(str);
}}
 The fruitsView TextView is accessed from the layout file main.xml and is assigned to the TextView
object fruitsView. The string array fruits from the layout file is accessed and assigned to the string
array fruitsArray.
 An empty string, str, is created. When we use a for loop, each element of Fruits Array is accessed
and appended to string str by \n. The string elements collected in the str element are assigned to the
TextView for display as shown below.

15
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Using Integer Arrays:


 Integer array is similar to creating a string array; the only difference is string array is replaced by
integer array. Let’s define an integer array in strings.xml file as shown below.
<resources>
<string name="app_name">StringArrayApp</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_string_array_app">StringArrayAppActivity</string>
<integer-array name="OddNumbers">
<item>1</item>
<item>3</item>
<item>5</item>
<item>7</item>
<item>9</item>
</integer-array>
</resources>
 We display integer array elements through a TextView. Let’s change activity_string_array_app.xml
file as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/oddnums_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

16
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 Write in the activity file StringArrayAppActivity.java to access the elements of the integer array
and to display them via TextView is shown below.

package com.androidunleashed.stringarrayapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class StringArrayAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity string_array_app);
TextView oddNumsView= (TextView) findViewById(R.id.oddnums_view);
int [] oddNumsArray= getResources().getIntArray(R.array.OddNumbers);
String str =" ";
for(int i = 0 ; i < oddNumsArray.length; i++) {
str+=oddNumsArray [i]+"\n";
}
oddNumsView. setText (str);
}
}
 The oddNumsView TextView from the layout file is accessed and mapped to the TextView object
oddNumsView. OddNumbers integer array is accessed and mapped to integer array oddnumsArray.
 Through a for loop, all array elements are accessed and appended to an empty string, str, separated
by \n. The content of the string str is then assigned to TextView, oddNumsView for display.

17
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

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.
 To support devices of different densities, we can store the images of low, medium, high, and extra
high resolutions in drawable-ldpi, drawable-mdpi, drawable-hdpi,and drawable-xhdpi directories.
 If Android doesn’t find the image in the drawable-hdpi folder, it searches for the image in other
directories to find the closest match.
 Let’s create a new Android project called DispimageApp and image file needs to be added to the
res/drawable folder. All image filenames should be lowercase and contain only letters, numbers, and
underscores.
 After we add images to res/drawable folders, gen folder is regenerated where R.java file resides.
R.java file includes a reference to the newly added image and used in layout file or other java code.
 The syntax for referencing image in the layout file is @drawable/image_filename. Referencing
image in java code is R.id.image_filename.
 To display image, add ImageView control to layout. We write code in layout file activity_disp_
image_app.xml as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/bintupic"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
 We see that an ImageView control is defined with ID image_toview to display through an Image.
We reference it via its src attribute. Syntax is: android:src=”@drawable/bintupic”
 This statement loads the image bintupic.png, which we pasted into the res/drawable folder. we don’t
need to write any java code for displaying the image.
 We can also specify the image for the ImageView control through Java code. To try this, let’s
remove src attribute then modify layout file, activity_disp_image_app.xml,appears as shown below
<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"

18
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:layout_height="match_parent">
<ImageView
android:id="@+id/image_toview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
 Let’s write code in Java activity file DispImageAppActivity.java to assign an image to ImageView
control as shown below.
package com.andriodunleashed.dispimageapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class DispImageAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disp_image_app);
ImageView image= (ImageView)findViewById(R.id.image_toview);
image.setImageResource(R.drawable.bintupic);
} }
 The statement, ImageView image = (ImageView) findViewById(R.id.image_toview); gets the
ImageView control from the layout file and stores it in an ImageView object called image.
 Image is an ImageView object that now refers to ImageView control placed in the layout file Via
setImageResource() method used in this statement, Image.setImageresource(R.drawable.bitupic);
 The image bintupic.png stored in the res/drawable folder is assigned to the ImageView control for
Display. After the application is run, we get output as shown below.

19
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Switching States with Toggle Buttons:


 ToggleButton toggles between the two states. A ToggleButton can only be in one state out of two
mutually exclusive states, for example, on and off.
 To Display a ToggleButtons, 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 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" />
 Let’s create a new Android project called ToggleButtonApp. This project consists of a TextView
and a ToggleButton. The TextView initially display some text, After we select the ToggleButton, the
text display through TextView changes, and after we select the ToggleButton again , the previous
text is redisplayed in the TextView control.
 After we define the two controls, code in layout file ativity_toggle_button_app.xml as shown below.
<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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="select the play button"
android:id="@+id/response"/>
<ToggleButton
android:id="@+id/Playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:texton="play"
android:textoff="Stop" />
</LinearLayout>
 We see that the TextView control is assigned the id response and is set to display the default text:
select the play button. ToggleButton is assigned ID playstop_btn is set to display play and stop in
the On and Off states.

20
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 To enable the ToggleButton to switch text via the TextView control when it is clicked we need to
write some java code in the ToggleButtonsAppActivity.java file shown below.
package com.andriodunleashed.ToggleButtonapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.view.View.OnClickListener;
import android.view.View;
public class ToggleButtonAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toggle_button_app);
final TextView resp = (TextView)this.findViewById(R.id.response);
final ToggleButton playstopButton = (ToggleButton)findViewById(R.id.Playstop_btn);
playstopButton.setChecked(true);
playstopButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(playstopButton.isChecked()){
resp.setText("stop button is toggled to play button");
}
else{
resp.setText("play button is toggled to Stop button");
}
}
});
}
}
 We can see that the response TextView and playstop_btn ToggleButton are accessed from the layout
file and are mapped to the TextView object resp and to the ToggleButton object playstopButton.
 ToggleButton is initially set to checked (On) state. An event handler oncliklistener is added to
ToggleButton playstopButton. It’s callback method, onClick() is executes when ToggleButton is
clicked.
 In the on click() method, we check the state of toggle button and change text displayed through the
TextView control accordingly. The state of the ToggleButton changes between the checked (on) and
unchecked (off) state on every click.

21
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 After the application is run, we get the output as shown below. We can see that the TextView
control displays the default text select the play button, and the caption displayed in the ToggleButton
is play. when the toggle button is selected its caption changes to stop, and the text in the TextView
changes to play button is toggled to stop button, as shown below
 when the toggle button is select again ,the caption in the toggle button changes back to play ,and the
text in TextView control changes to stop button is toggled to play button, as shown below

 We can add the android:gravity and android:layout_gravity attributes to <TextView> and


<ToggleButton> tags in the layout file to centre the in the text in the TextView control and align
ToggleButton at the centre position in respect to its container by following statement:
For TextView, android: gravity=”centre”
For ToggleButton, android: layout-gravity=”centre”
 we can also add a background image into the ToggleButton by adding the android:background
attribute to the <ToggleButton> tag in the layout file. As shown below:
android:background =”@drawable/ic_launcher”
 The ic_launcher.png image is the built-in image resource provided by ADT that can be seen in the
res/ drawable folder. After we add the android:layout_gravity and android:background attributes, the
ToggleButton appears as shown below.

22
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 To display different background images for the on and off states of the toggle button, we need to add
two images play.png and stop.png into the res/drawable folders.
 To make this these images display as back ground images in the ToggleButton control on and off
states, add some java code to ToggleButtonsAppActivity.java file as shown below.
package com.andriodunleashed.ToggleButtonapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.view.View.OnClickListener;
import android.view.View;
public class ToggleButtonAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toggle_button_app);
final TextView resp = (TextView)this.findViewById(R.id.response);
final ToggleButton playstopButton = (ToggleButton)findViewById(R.id.Playstop_btn);
playstopButton.setChecked(true);
playstopButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(playstopButton.isChecked()){
playstopButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.play));
resp.setText("stop button is toggled to play button");
}
else{
playstopButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.play));
resp.setText("play button is toggled to Stop button");
}
}
});
}}
 We can see that the newly added code access the resources object through the getResources()
method and drawable resources are access by supplying the resources ID of the play.png and
stop.png images to the getDrawable() method.
 The images accessed are then applied as the background of the ToggleButtons on and off states. lets
remove the text of the on and off states and modify on and off states as shown below.

23
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:textOn=” “
android:textOff=” “
 Now we replace ic_launcher.png image with play.png image by setting following attribute:
android:background=”@drawable/play”
 Above attribute displays play.png on application startup.layout file after appling these change as
shown below
<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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="select the play button"
android:gravity="center"
android:id="@+id/response"/>
<ToggleButton
android:id="@+id/Playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/play"
android:textOn=""
android:textOff="" />
</LinearLayout>
 After application is run, play.png appears in ToggleButton on state. after we select play Button,
stop.png appears in ToggleButton off state.

24
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Creating Image Switcher Application:


 Here application initially display image through ImageView control with ToggleButton at bottom of
screen. when ToggleButton is clicked, image displays in ImageView is changed.
 Let’s add 32 images bintupic.png and bintupic2.png to res/drawable folder then R.java is
regenerated. It allows us to refer these images to layout file or java file.
 .We need to modify our layout file, main.xml, to do the following two things:
1. Assign the bintupic.png image to an ImageView control to be displayed on startup.
2. Add an ToggleButton to initiate image switching
 After we implement these tasks, our activity_disp_image_app.xml file appears as shown below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/bintupic1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<ToggleButton
android:id="@+id/change_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textOn="Previous Image"
android:textOff="Next Image"
android:layout_marginTop="10dip"/>
</LinearLayout>

 We see that the image_toview ImageView control is set to display bintupic.png. Below the
ImageView control, a change_image ToggleButton is displayed at the center. The text of
ToggleButton on and off states is set to PreviousImage and NextImage.
 To enable ToggleButton to switch images, we need to write code in the DispImageAppActivity.java
file as shown below.

25
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

package com.androidunleashed.dispimageapp;
import android.app.Activity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.view.View;
import android.view.View.OnClickListener;
public class DispImageAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disp_image_app);
final ImageView image=(ImageView) findViewById (R.id.image_toview);
final ToggleButton changeButton=(ToggleButton)findViewById(R.id.change_image);
changeButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (changeButton.isChecked()) {
image.setImageResource(R.drawable.bintupic2);
}
else{
image.setImageResource(R.drawable.bintupic1);
}
}
});
}
}

 The image_toview ImageView control is accessed from the layout file and is mapped to the
ImageView object image. ToggleButton control is accessed from the layout file and is mapped to the
ToggleButton object ChangeButton.
 An event handler, OnClickListener, is added to the ToggleButton. Its callback method, onclick(), is
implemented. This is executed when the ToggleButton is clicked.
 After application is run, we find that the first, bintupic.png, is displayed through the ImageView
control along the ToggleButton and the text NextImage is displayed at the bottom.
 When the ToggleButton is clicked, the image displayed through the ImageView control switches to
bintupic2.png, and the button text of the ToggleButton changes to PreviousImage, as shown below.

26
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Scrolling Through ScrollView:


 ScrollView is a special type of control that sets up a vertical scrollbar in a view container. It used to
display views that are too long to be accommodated in a single screen.
 The ScrollView can have only one child, so view container layout is used as child. All the child
controls in the layout have one continuous scrollbar.
 Let’s create a new Android project called ScrollViewapp. in this application, we place three images,
one below the other. all the three images cannot fit into a single screen , so we use the ScrollView
control to scroll them vertically.
 First copy the the three images bm1.png, bm2.png and bm3.png in res/drawable folders. To display
images in the application, we use the ImageView control and set the android.src attribute of each of
them to refer to files bm1.png, bm2.png, and bm3.png.
 Layout file activity_scroll_view_app.xml with three ImageView controls appears as shown below
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/bintupic1"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity= "center"/>
<ImageView
android:id="@+id/image_toview2"

27
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:src="@drawable/bintupic2"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity="center"
android:layout_marginTop="10dip"/>
<ImageView
android:id="@+id/image_toview3"
android:src="@drawable/bintupic3"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity="center"
android:layout_marginTop="10dip"/>
</LinearLayout>
 Let’s write code into the activity file ScrollViewappactivity.java as shown below
package com. android unleashed. Scroll view app;
import android.app.Activity;
import android.os.Bundle;
public class ScrollViewAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ScrollView_app);

}
}
 After the application is run, we see the output shown below. The first two images are visible, and the
third one is hidden. The application does mot scroll, so there is no way to see the hidden image.
 To add scrolling to application, we add scroll control to the layout file and make it the parent of the
existing liner layout Container.
 After we add Scroll view control, the layout file activity_scroll_app.xml appears as show in below.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@i+d/scrollwid"
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"

28
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image_toview"
android:src="@drawable/bintupic1"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity= "center"/>
<ImageView
android:id="@+id/image_toview2"
android:src="@drawable/bintupic2"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity="center"
android:layout_marginTop="10dip"/>
<ImageView
android:id="@+id/image_toview3"
android:src="@drawable/bintupic3"
android:layout_width="200dip"
android:layout_height="250dip"
android:layout_gravity="center"
android:layout_marginTop="10dip"/>
</LinearLayout>
</ScrollView>

Use of the android: fill Viewport Attribute:


 When the size of the child control(s) is larger than the display applying a scrolling effect to the child
controls. However, if the size of the child control(s) is smaller than the display, the scroll View
shrinks to match the size of its content.
 When set to true, the android:fillViewport attribute makes the child control(s) of the scroll View
expand to the display. The linear layout container holding the three image view controls is made
child of a scroll view control.
 The scroll view control is used for vertical scrolling. For horizontal scrolling, horizontal scroll view
is used.

29
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Playing audio:
 To learn the Methods used to play, pause and resume the audio. Let’s make a new android project
called playaudioapp. 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 is not created automatically, so we need to create it manually.
 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.
 In the raw folder, copy an audio file called song1.mp3. The java class R.Java file is automatically
regenerated after the audio file is added to the application allowing us to access it.
 In this application, we want to display a TextView and a Button control. TextView displays
instruction(s), and the button control initiates an action. To add the two controls, write the code in
the layout file activity_play_audio_app.xml as shown below.
<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="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="playing audio"/>
<Button

30
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:id="@+id/playbtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="play"/>
</LinearLayout>
 The TextView is set to display the text playing audio. The ID and caption assigned to the button
controls are playbtn and play. To play the audio when the play button is clicked, write the code as
shown below into the activity file playAudioAppActivity.java
package com.android unleashed.playaudioapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
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);
Button playButton=(Button)findViewById(R.id.playbtn);
playButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
MediaPlayer mp= MediaPlayer.create(PlayAudioAppActivty.this,R.raw.song);
mp.start();
}
});
}
}
 playbtn button controls is captured from the layout and mapped to the button object playButton. An
event handler, onclicklistener, is added to the playbutton object.
 its callback method, onClick(), is implemented, which is executed when the play button is clicked.
In the onClick() method, we write an instance, mp, of the MediaPlayer by calling the media
player.create() method.
 To the MediaPlayer instance mp, we pass the reference of our mp3songs, song1.mp3, that we placed
in the raw folder. Finally we call the MediaPlayer start() method to play the song.
 after the appliction is run, we get a TextView showing the text playing audio and a button control
with the text play a shown below. when the play button is clicked the audio song1.mp3 is played.

31
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 We can control the volume of audio with volume switches on the side of android emulator. we can
also display an image on button control by adding following attributes to <button>element:
1. android:drawableTop--the image is display the above button text.
Example, android:drawableTop="@drawable/ic_launcher"
2. android;drawablebutton---the image is displayed below the button text.
3. android;drawableleft---the image is displayed to the left of the button text.
4. android;drawableright--the image is displayed to the right of the button text.

 PlayAudioApp works fine, but it does not have the stop or pause button to stop and resume playing
the audio. To switch the status of the audio from the play to stop and vice versa, we replace button
control with the ToggleButton control. the layout of file activity_play_audio_app.xml appers as
shown below
<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="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="playing audio"
32
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:gravity="center"
android:id="@+id/responce"/>
<ToggleButton android:id="@+id/playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="stop"
android:textOff="play"
android:layout_gravity="center"/>
</LinearLayout>
 we can see that a playstop_btn ToggleButton is defined as the test stop and play for its on and off
states. the ToggleButton is set to appear at the center of the linear layout container through the
android:layout_gravity="center" attribute.
 TextView control is aligned at the center through the andriod:gravity="center" attribute. ID reponse
is assigned to the TextView so that we can access it and change text in dynamically at runtime. To
stop and resume the audio with in click of ToggleButton we write the java code as shown below.

package com.androidunleashed.playaudioapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.media.MediaPlayer;
import android.view.View.OnClickListener;
public class playAudioAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_audio_app);
final TextView response=(TextView)this.findViewById(R.id.response);
response.setText("select play buton on the play audio");
final MediaPlayer mp=MediaPlayer.create(playAudioAppActivity.this,R.raw.song);
final ToggleButton playstopbutton=(ToggleButton)findViewById(R.id.playstop_btn);
playstopbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(playstopbutton.isChecked()){

33
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

response.setText("select stop button on the play audio");


mp.start();
}
else
{
response.setText("select play button on the play audio");
mp.pause();
}
}
});
}
}

 The TextView and ToggleButton controls with the IDs response and playstop_button are accessed
from layout file and mapped to TextView and ToggleButton objects response and playstopButton.
 Instance, mp, of the MediaPlayer is created by calling media player’s create() method and pass
song1.mp3 to create() method.
 Event handler onclicklistener, is added to ToggleButton object. when ToggleButtonis clicked its call
back method onclick() check the status of ToggleButton.
 If ToggleButton is in on state, we call MediaPlayer Start() method to play audio and set text
TextView to select stop button to stop audio. If ToggleButton is clicked, audio is stopped.
 If ToggleButton is in off state, we call MediaPlayer Pause() method to stop audio and set text
TextView to select play button to stop audio. If ToggleButton is clicked, audio is resumed.
 After application run, we get output as shown below

34
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 Display play and stop images in the ToggleButton instead of plain text, We need to add two image,
play.png and stop.png, to the four res/drawable folders of this project.
 After we add the two images, the java class, R.java is regenerated containing the reference to the
two images and reset the android:texton and android:textoff attribute of the <ToggleButton> tag in
the layout file main.xml, as shown here:
android:textOn=" "
android:textOff=" "
 we need to use the andriod:background attribute to display the play.png image in the ToggleButton
on startup. To do this, we need to add the following statement in the<ToggleButton>tag :
android:background="@drawable/play"
 After we apply these modification, layout file activity_play_audio_app.xml appears as shown below.
<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="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="playing audio"
android:gravity="center"
android:id="@+id/response"/>
<ToggleButton android:id="@+id/playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn=""
android:textOff=""
android:layout_gravity="center"
android:background="@drawable/play"/>
</LinearLayout>

 After clicking ToggleButton, background image of ToggleButton is changed from play.png to


stop.png. we need to add two statements to playAudioAppActivity.java as shown below
package com.androidunleashed.playaudioapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

35
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.media.MediaPlayer;
import android.view.View.OnClickListener;
public class playAudioAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_audio_app);
final TextView response=(TextView)this.findViewById(R.id.response);
response.setText("select play buton on the play audio");
final MediaPlayer mp=MediaPlayer.create(playAudioAppActivity.this,R.raw.song);
final ToggleButton playstopbutton=(ToggleButton)findViewById(R.id.playstop_btn);
playstopbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(playstopbutton.isChecked()){
response.setText("select stop button on the play audio");
playstopbutton.setBackgroundDrawable(getResources().getDrawable(R.drawable.stop));
mp.start();
}
else
{
response.setText("select play button on the play audio");
playstopbutton.setBackgroundDrawable(getResources().getDrawable(R.drawable.play));
mp.pause();
}
}
});
}
}

 We can see that newly added code allows access to the stop.png and piay.png images from drawable
resources by supplying the image filenames to the getDrawable() method of the Resources object.
 Depending on the current state of the ToggleButton (on or off), the accessed images are assigned to
appear as its background. After the application is run, we see output as shown below.

36
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

Playing Video:
 To play video in an application, Android provides a VideoView control, which, along with the
MediaController, provides several buttons for controlling video play.
 These buttons allow us to play, pause, rewind, and fast-forward the video content displayed via the
VideoView control. To understand the steps for playing a video, let's create a new Android project
called playvideoApp.

Loading Video on SD card:


 Emulator must running while loading video onto SD card. To load video onto SD card, follow these
steps:
1. Open DDMS perspective by selecting window, open perspective, DDMS option
2. In DDMS perspective, open file explorer by selecting window, show view, file explorer.
3. If you can’t see running emulator anywhere, open the devices view by selecting window, show
view, Devices option. We are able to see all running emulators, and we select one that we use to
play video.
4. File explorer view, we see different folders and files in emulator.

 Navigate the tree and expand the mnt node. In mnt node, select the sdcard node. If you hover your
mouse over two buttons on the top right side of File Explorer, you see messages Pull a file from the
device and Push a file onto the device.

37
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 Click button Push a file onto the device. We see a dialog box for choosing a video from the disk
drive. After selecting a video, select the OK button to load the selected video onto the SD Card.
 Implement playing video, we add VideoView and Button Controls to activity_play_video_app.xml
as shown below.
<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="wrap_content">
<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"

38
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

android:layout_width="match_parent"/>
</LinearLayout>
 We see that a VideoView and a Button control have been added to application, where VideoView
widget is used for displaying video, and the Button control plays the video when selected.
 To assign the video to the VideoView control, write the code as shown below in the Java activity file
PlayVideoAppActivity.java.
package com.androidunleashed.playvideoapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.VideoView;
import android.widget.MediaController;
import android.view.View.OnClickListener;
public class PlayVideoAppActivity extends Activity{
@Override
public void onCreate(Bundle savedinstanceState) {
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();
}
});
} }
 We capture the VideoView control from the layout and map it to the VideoView object. Then we
use MediaController and set it the media controller of the VideoView object.
 The VideoView object is used for displaying video content and button controls that enable us to
perform play, pause, rewind, or fast-forward actions on the video with MediaController by calling
setMediaController().
 We use the setvideoPath() method of the VideoView object to refer to an SD card for the video.mp4
file. We can also use setvideoURI() method to access the video from the Internet.

39
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 After setting the focus to VideoView control through requestFocus() method, we use its start()
method to start video. After run the application, we get output showing below after click the button.

DisPlaying Progress with ProgressBar:


 While executing such tasks like as downloading a file, installing software and playing audio and
video …, we need to continually inform user about 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.
 Circular indicator is used when there is no specific duration for completion of the task. Another
mode of ProgressBar is horizontal ProgressBar.
 horizontal progress bar that displays an indicator showing the amount of a task that is completed .
To make the ProgressBar display in the form of a horizontal bar, set its style attribute to
@android:style/Widget.ProgressBar.Horizontal, as shown below:
<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 progressBar:
1. Widget.ProgressBar.Horizontal
2. Widget.ProgressBar.Small
3. Widget.ProgressBar.Large
4. Widget.ProgressBar.Inverse

40
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT
5. Widget.ProgressBar.Small.Inverse
6. Widget.ProgressBar.Large.Inverse
 ProgressBar for Widget.ProgressBar.Horizontal, Widget.ProgressBar.Small and Widget.ProgressBar
are shown below.

 Inverse style is used when our application uses a light-colored theme, such as a white background.
The minimum value of the ProgressBar is by default 0. The maximum value of the ProgressBar is
set by the android:max attribute. For example,
android:max="100"
 We can also set the maximum value of the ProgressBar through a setMax() Java method. The
following code sets the maximum value of the ProgressBar to 100:
progressBar.setMax(100);
 To display progress through an indicator in the ProgressBar control, we call the setProgress()
method of the ProgressBar class, passing in an integer value to indicate the progress. For example,
progressBar.setProgress(60); where progressBar is an object that represents the ProgressBar control.
 To understand the ProgressBar, Let's create android project called ProgressBarApp. In this
application, we play an audio, and the ProgressBar displays the progress of the audio.
 For this application, we use a Textview, a ToggleButton, and a ProgressBar control. After add
controls layout file activity_progress_bar_app.xml as shown in below.
<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="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="playing audio"
android:gravity="center"
android:id="@+id/response"/>
<ToggleButton android:id="@+id/playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn=""
android:textOff=""
android:layout_gravity="center"
android:background="@drawable/play"/>

41
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

<ProgressBar
android:id="@+id/progressbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_marginTop="20dip" />
</LinearLayout>
 To display Play and Stop images in the ToggieButton, we copy the images piay.png and stop.png to
the res/drawabie folders. For playing audio, create a folder called raw in the res folder and then copy
the audio file song1.mp3 into it.
 To play and stop the audio with the ToggieButton control and to display the progress of the audio in
ProgressBar control, write code as shown in below in the activity file ProgressBarAppActivity. java.
package com.androidunleashed.progressbarapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ToggleButton;
import android.view.View;
import android.widget.TextView;
import android.media.MediaPlayer;
import android.view.View.OnClickListener;
import android.widget.ProgressBar;
import android.os.Handler;
public class ProgressBarAppActivity extends Activity {
MediaPlayer mp;
ProgressBar progressBar;
private final Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_bar_app);
final TextView response = (TextView)this.findViewById(R.id.response);
response.setText("Select Play button to play audio");
progressBar=(ProgressBar)findViewById(R.id.progressbar);
mp = MediaPlayer.create(ProgressBarAppActivity.this,R.raw.song);
final ToggleButton playStopButton = (ToggleButton)findViewById(R.id.playstop_btn);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());

42
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

playStopButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (playStopButton.isChecked()) {
response.setText("Select Stop button to stop audio");
playStopButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.stop));
mp.start();
updateProgressBar();
}
else {
response.setText("Select Play button to play audio")
playStopButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.play));
mp.pause();
}
}
});
}
private void updateProgressBar() {
progressBar.setProgress(mp.getCurrentPosition());
if (mp.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
updateProgressBar();
}
};
handler.postDelayed(notification,1000);
}
}
}
 We see that the Textview, ProgressBar, and ToggleButton controls with the IDs response,
progressbar, and playstop_btn are accessed from the layout file main.xml and assigned to their
respective button objects (response, progressBar, and playStopButton).
 An instance is created by calling the MediaPlayer's create () method. The MP3 song reference,
song1.mp3, which we stored in the raw folder, is passed to the create() method. The minimum value
of the ProgressBar control is set to 0, and its maximum value is set equal to duration of the audio.
 An object handler of the Handier class is used to send and process a Runnable object. Handier is the
preferred threading technique used to perform tasks in the background.

43
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 When a message or runnable object is passed to the Handler, it is saved into the message queue. The
UI thread pulls the message or runnable object from the queue and executes it.
 The UI thread is automatically created when an application is launched and is the one that handles
events related to the widgets or controls used in the application.An event handler, OnclickListener,
is added to the ToggleButton object playStopButton. Whenever the ToggleButton is clicked, its
callback method, onclick(), is executed.
 In onClickO method, If ToggleButton is set to on state, we call MediaPlayer's start() method to play
audio and set Textview to display text select stop button to stop audio and stop.png is displayed as
background. if ToggleButton is pressed again, audio will be stopped and play.png is displayed as
background.
 In updateprogressbar() method, we update progress bar periodically by duration of audio. Runnable
object notification is created and added to the message queue through the postDelayed() method of
the handler object.
 The runnable object is schedule to run after 1000 milliseconds and it attached to UI thread. The run()
method, which is executed after every 1000 milliseconds, calls the updateprogressbar() method to
update the progress bar indicator periodically.
 After the application is run, we get the output as shown below

Using Assets:
 The external files containing information such as strings, Images and Audio that reside in the
res/folder are consider resources. Besides the res/directory, android provides another directory,
assets/, where we can keep asset files to be included in our application.
 Content placed in the assets/directory is maintained in raw file format, and no IDs are generated
from these files. To read the content from the assets/folder in an android application, we use the
asset manager, which reads the content from the external files in the form of a stream of bytes.

44
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

 In the application that we are going to create as an example, We add text file to the assets folder then
accessed it by Asset Manager and is displayed in a TextView.
 Create a new Android project called AssetsApp. Add file called info.txt to the project by copying and
pasting it into assets folder in the package Explorer Window. Because we want content of info.txt be
displayed through a TextView, let’s modify layout file activity_assets_app.xml as shown below.
<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="wrap_content">
<TextView
android:id="@+id/file_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dip"
android:textStyle="bold"/>
</LinearLayout>
 The content to be displayed via TextView is set to appear in bold and 15dip text. Write code in java
activity file AssetsAppActivity.java for read the content from the file, info.txt is placed in the assets
folder and is displayed via the TextView control.
package com.androidunleashed.assetsapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.InputStream;
import android.content.res.AssetManager;
import java.io.IOException;
public class AssetsAppActivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assets_app);
TextView fileview=(TextView)findViewById(R.id.file_view);
InputStream input;
AssetManager assetManager =getAssets();
try{
input= assetManager.open("info.txt");

45
III.BTECH II-SEM, AI&IOT: MOBILE APPLICATION DEVELOPMENT

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");
}
}
}
 We see that TextView is accessed from the layout file and is mapped to the TextView object
fileview. Because the assets are read using an asset Manager by calling the getAssests() method.
 The getAssets() method opens the Assets folder and returns a handle to this folder. To read content
from the file, we need an Input Stream object, so the open() method of the Asset Manager class is
called, passing the file name info.txt to it as a parameter.
 The open() method opens the file info.txt in the assets folder and returns it in the form of Input
Stream, which is assigned to the Input Stream instance input. The size of the file is computed by
calling an available() method on the Input Stream class.
 A buffer equal to the file size is defined, and then file content is read via the Input Stream object into
the buffer. The Input Stream object is closed. The file content in the form of bytes stored in the
buffer is converted into a string and is assigned to the TextView control for display.

46
IV.BTECH I-SEM, CSE: MOBILE APPLICATION DEVELOPMENT

You might also like