unit 2 Resources
unit 2 Resources
Resources
Resources include text data, bitmaps, audio, videos, and other items used by the Android
application.
Most commonly resources are kept separately in XML files and accessed in Java code
through the IDs assigned to them.
Resources in Android refer to the external files that hold the information, such as strings,
images, layouts, and audio, to be supplied to an Android application.
Because resources are external, we can maintain and modify them whenever we want
without disturbing the code.
For example, the strings resource keeps the strings used in an Android application.
Changing the string content in the resource file is easier when compared to applying
changes to hard-coded strings that are scattered in the application code.
Three categories
Resources are broadly divided into three categories—values, drawable, and layout—and
are stored in the res folder of our project hierarchy.
The values resources in turn represent resources such as strings, colors, dimensions,
styles, and string or integer arrays.
All resource types have a respective subfolder in the res folder. The ADT Wizard
automatically creates a res folder that contains subfolders for the values, drawable, and
layout resources, as shown in Figure 4.1.
Figure 4.1. The res folder showing the nested drawable (drawable-hdpi, drawable-
ldpi, drawable-mdpi) layouts and values folders and their content
NOBLE CS DEPT 1
Unit II
Chapter 4 Utilizing Resource Media
Types of Resources
1. drawable folder—
Depending on the target platform chosen, our application can have either a
single directory, drawable, or four directories, drawable-ldpi, drawable-
mdpi, drawable-hdpi, and drawable-xhdpi, where we can store the images with
different screen resolutions are stored in the respective directories.
That is, the images of low, medium, high, and extra high resolutions are stored
in the drawable-ldpi, drawable-mdpi, drawable-hdpi, and drawable-
xhdpi directories, respectively.
2. layout folder—This folder contains a layout file automatically created for us. The
default name assigned to this file is activity_main.xml, but we can assign any name to it.
3. menu folder—This folder contains XML file(s) that represent application menus.
Again, the default name assigned to the menu file that is automatically created for us
is activity_main.xml, but we can change the name if we want.
4.values folder—This folder by default contains a strings.xml file that we can use to
define values resources that include strings, colors, dimensions, styles, and string or integer
arrays. The following is a list of some XML files that we can create in the values folder:
• arrays.xml—For defining arrays resources
• colors.xml—For defining color resources that define color values
• dimens.xml—For defining dimension resources to standardize certain application
measurements
• strings.xml—For defining string resources
• styles.xml—For defining styles resources to format or change the appearance of our views and
application
• values-v11—The folder contains the styles.xml file that declares the holographic theme,
which is used when the application runs on Android 3.0 (API Level 11) or higher.
• values-v14—The folder contains the styles.xml file that declares the DeviceDefault theme,
which is used when the application runs on Android 4.0 (API Level 14) or higher.
NOBLE CS DEPT 2
Unit II
Chapter 4 Utilizing Resource Media
String Resources:
<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>
The two string resources with the name attributes hello and app_name are assigned to
the TextView (in main.xml) and label attribute of the Activity tag
(in AndroidManifest.xml) to display the name of the activity and the application name,
respectively, while running the project.
Let’s modify the strings.xml file to appear as shown in Listing 4.2.
Listing 4.2. Code Written in the strings.xml File
<resources>
<string name="app_name">ValuesResourcesApp</string>
<string name="menu_settings">Settings</string>
NOBLE CS DEPT 3
Unit II
Chapter 4 Utilizing Resource Media
<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> element represents one string resource. Besides the text for the string
resource, it contains a name property used to assign a unique resource ID to the string.
That is, the names assigned to the four string
resources, app_name, str_name, str_address, and str_message, are the resource IDs of
the respective strings, and we can use these resource IDs in other resource files or the
Java code for accessing the respective string resources.
We can use the string resources of the preceding XML file in other resource files by
using the following syntax:
@string/resource_ID
For example, to access the string resource with the resource ID str_address in another
resource file, we use the following code:
@string/str_address
All the string resources mentioned in the preceding string resource file will be compiled and
placed in the R.java file.
Java code:
In the Java code, we can access the resources from the R.java file, using the following syntax:
R.string.resource_ID
Hence, 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 and pass the resource ID of the concerned string resource to
access it in Java code. Hence, the complete command to access the string resource with the
resource ID str_address is
getString(R.string.str_address);
NOBLE CS DEPT 4
Unit II
Chapter 4 Utilizing Resource Media
To access the string resources defined in the file strings.xml and to apply them to
the TextView controls, the layout file activity_values_resources_app.xml may be modified to
appear as shown in Listing 4.3.
Listing 4.3. Code Written in the Layout File activity_values_resources_app.xml
<LinearLayoutxmlns: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>
NOBLE CS DEPT 5
Unit II
Chapter 4 Utilizing Resource Media
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);
TextViewaddressView=(TextView)findViewById(R.id.address_view);
addressView.setText(strAddress);
}
}
1. The string resource with the resource ID str_address is accessed and assigned to the
String object strAddress.
2. The TextView with the ID addressView is accessed from the layout and is mapped to
the TextView object addressView.
3. The content of the string resource that is saved in the strAddress object is assigned to
the TextView to display.
4. That is, the content of the string resource str_address is assigned to a TextView so it will
be displayed on the screen.
Dimension Resources
Dimension resources are used for standardizing certain application measurements.
These resources can be used to specify the sizes for fonts, layouts, and widgets.
Also, we can modify the size of any control in the application without changing the
code.
Besides this, we can define dimensions for different screen resolutions and densities to
support different hardware.
NOBLE CS DEPT 6
Unit II
Chapter 4 Utilizing Resource Media
dimens.xml
To try out dimension resources, let’s open the application ValuesResourcesApp and add
an XML file called dimens.xml to the values folder. To the dimens.xml file, add the code as
shown in Listing 4.5.
Listing 4.5. Code Written in the dimens.xml File
1. We can see that the dimension resource is defined through the dimen element.
2. The dimen element contains a numerical value followed by unit of measurement.
3. Like other resources, it includes the name property to specify the ID of the resource.
• px—Pixels
• in—Inches
• mm—Millimeters
• pt—Points
• dp—Density-independent pixels based on a 160-dpi (pixel density per inch) screen
• sp—Scale-independent pixels
In the strings.xml file, we have defined three dimension resources: 15dp, 15sp, and 20pt,
represented by the three resource IDs small_size, medium_size, and large_size,
respectively.
Let’s apply the dimension resources to
our TextView controls name_view, address_view, and message_view. through the
layout file followed by Java code.
To apply dimension resources to the TextView controls,
modify activity_values_resources_app.xml to appear as shown in Listing 4.6.
Listing 4.6. The Layout File activity_values_resources_app.xml on Applying Dimension
Resources to TextView Controls
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
NOBLE CS DEPT 7
Unit II
Chapter 4 Utilizing Resource Media
<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>
android:textSize="@dimen/small_size"
and
android:textSize="@dimen/large_size"
access the two dimension resources small_size and large_size and apply to the
two TextViews with the IDs name_view and message_view, respectively. Their text size is set
to 15px and 20sp, respectively.
Java code:
Now let’s see how to apply dimension resources to a View via Java code.
The TextView to which we want to apply the dimension resource is accessed from the
layout file and mapped to the TextView object addressView.
Thereafter, we access our Resources object by calling the getResources() method on our
activity object.
Then, through the Resources object, we access the dimension by supplying its resource
ID to the getDimension() method.
NOBLE CS DEPT 8
Unit II
Chapter 4 Utilizing Resource Media
Figure 4.3. Different dimensions applied to the three TextViews via 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. .
The Alpha channel represents the transparency.
We can specify the color either through single-character hex values or double-character
hex values formats, as shown here:
1. #RGB—For example, #F00 for a Red color.
2. #RRGGBB—For example, #FF0000 for a Red color
3. #ARGB—For example, #5F00 for a Redcolor with an Alpha of 5.
4. #AARRGGBB—For example, #50FF0000 for a Redcolor with an Alpha of 50.
colors.xml
To apply color resources to our application ValuesResourcesApp, let’s add an XML file
called colors.xml to the values folder. In the colors.xml file, define a few color resources by
writing the following lines of code in it:
NOBLE CS DEPT 9
Unit II
Chapter 4 Utilizing Resource Media
This code block defines three color resources that represent the three colors red, green,
and blue (bit transparent) through the resource IDs red_color, green_color,
and blue_alpha_color, respectively.
To apply color resources via the layout file activity_values_resources_app.xml, let’s modify it
to appear as shown in Listing 4.7.
Listing 4.7. The Layout File activity_values_resources_app.xml on Applying Color Resources
<LinearLayoutxmlns: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>
android:textColor="@color/red_color"
and
android:textColor="@color/blue_alpha_color"
access the color resources with the IDs red_color and blueAlpha_color, from the resource file
and assign them to the text of the two TextViews, name_view and message_view. This changes
their color to red and blue, respectively.
NOBLE CS DEPT 10
Unit II
Chapter 4 Utilizing Resource Media
Java code
To apply the color resource to the TextViewaddress_view, we use Java code. Add the
following lines of code to the Java file ValuesResourcesAppActivity.java to access the color
resource and apply it to the desired View:
int addressColor=this.getResources().getColor(R.color.green_color);
addressView.setTextColor(addressColor);
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);
TextViewaddressView=(TextView)findViewById(R.id.address_view);
addressView.setText(strAddress);
float addressSize= this.getResources().getDimension(R.dimen.medium_size);
addressView.setTextSize(addressSize);
int addressColor=this.getResources().getColor(R.color.green_color);
addressView.setTextColor(addressColor);
}
}
NOBLE CS DEPT 11
Unit II
Chapter 4 Utilizing Resource Media
Figure 4.4. The three TextViews displayed in different colors applied via the Color Resource.
The TextView controls are distinguished through different sizes.
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.
That is, instead of applying attributes individually to the components of our application,
we can create a style incorporating all these attributes and quickly apply it instead.
Through styles, we can apply a consistent dynamic look to our Views, Activity, and to
the overall application.
Also, we can easily change the appearance of our Views and application by simply
specifying a different style or modifying the properties of the existing style, all without
disturbing the Java code.
1. A style is created by using a style element with one or more item child elements.
2. The style element includes a name property to specify the resource ID.
3. Each item element includes a name property to define the attributes such as
color, font, and so on.
4. An item element defines an attribute and its value shown in this syntax:
<resources>
<style name="resource_ID">
<item name="attribute_name">value </item>
</style>
</resources>
NOBLE CS DEPT 12
Unit II
Chapter 4 Utilizing Resource Media
<LinearLayoutxmlns: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"
style="@style/style1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"/>
<TextView
android:id="@+id/address_view"
style="@style/style2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_address" />
<TextView
android:id="@+id/message_view"
style="@style/style3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message" />
</LinearLayout>
We can see that style1, style2, and style3 are applied to the
three TextView controls name_view, address_view, and message_view, respectively.
Hence, the content of the first TextView appears in green, serif font and 30sp in size.
Similarly, the content of the second TextView appears in a blue foreground color, red
background color, sans font, 30sp in size, and the spacing (padding) between the text
and the TextView on all four sides is 10dip.
The content in the third TextView appears in monospace font, green foreground color,
black background color, size 30sp in and the text appears at the center of the TextView.
When the application is run, we get the output as shown in Figure 4.5.
Figure 4.5. The three TextViews with different styles applied to them
NOBLE CS DEPT 13
Unit II
Chapter 4 Utilizing Resource Media
Applying Themes
We can apply the style element to an entire Activity or application by adding
the android:theme attribute to the Android manifest.
For example, after we add the android:theme attribute to the <activity> element in the
Android manifest, all the attributes of the style are applied to every View within the
Activity.
Similarly, after we add the android:theme attribute to the <application> element in the
Android manifest, all the attributes of the style are applied to all the activities in the
application.
The AndroidManifest.xml file of our application ValuesResourcesApp originally appears as
shown in Listing 4.12.
Listing 4.12. Default Code in the AndroidManifest.xml File
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.valuesresourcesapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".ValuesResourcesAppActivity"
android:label="@string/title_activity_values_resources_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let’s apply style3, which we defined in the styles.xml file, to the entire application by
modifying the android:theme attribute in AndroidManifest.xml file, as shown in bold
in Listing 4.13.
Listing 4.13. Code in the AndroidManifest.xml File on Modifying
the android:theme Attribute
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.valuesresourcesapp"
android:versionCode="1"
NOBLE CS DEPT 14
Unit II
Chapter 4 Utilizing Resource Media
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/style3" >
<activity
android:name=".ValuesResourcesAppActivity"
android:label="@string/title_activity_values_resources_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
To see the impact of applying the style to the entire application, we need to remove the
styles in the layout file that were applied to the individual TextView controls. So,
modify activity_values_resources_app.xml to appear as shown in Listing 4.14.
Listing 4.14. The Layout file activity_values_resources_app.xml on Removing Styles
<LinearLayoutxmlns: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"
NOBLE CS DEPT 15
Unit II
Chapter 4 Utilizing Resource Media
android:text="@string/str_message" />
</LinearLayout>
After the application is run, we find that the content of all three Views appears
in monospace font, green foreground color, black background color, 30sp in size, and the text
appears at the center of the container, as shown in Figure 4.6.
Arrays
Arrays refer to a collection of values or elements.
Arrays are known for their capability of direct reference; that is, any element in an array
can be referenced directly by specifying its index/subscription value.
Arrays are considered to be one of the most flexible data sources for an application.
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
As the name suggests, the 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 the 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.
NOBLE CS DEPT 16
Unit II
Chapter 4 Utilizing Resource Media
<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>
We can see that the string array fruits consists of five string elements,
namely Apple, Mango, Orange, Grapes, and Banana.
Let’s make these string elements appear in a TextView.
Add a TextView to the layout file. The code appears as shown in Listing 4.16.
Listing 4.16. Code in the Layout File activity_string_array_app.xml on Adding
the TextView Control
<LinearLayoutxmlns: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
NOBLE CS DEPT 17
Unit II
Chapter 4 Utilizing Resource Media
android:id="@+id/fruits_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
we write the code in the Java file StringArrayAppActivity.java as shown in Listing 4.17.
Listing 4.17. Code Written in the Java Activity File StringArrayAppActivity.java
package com.androidunleashed.stringarrayapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class StringArrayAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_string_array_app);
TextViewfruitsView = (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);
}
}
1. The fruitsViewTextView is accessed from the layout file main.xml and is assigned to
the TextView object fruitsView.
2. Also, the string array fruits from the layout file is accessed and assigned to the string
array fruitsArray.
3. That is, we can now access the string elements of the string array from the layout file in
the Java code via the string array fruitsArray.
4. An empty string, str, is created. When we use a for loop, each element of fruitsArray is
accessed and appended to the string str.
5. A new-line character, \n, is added between every string element to display them on
separate lines.
6. The string elements collected in the str element are assigned to
the TextViewfruitsView for display.
7. After the application is run, all the string elements are displayed in the TextView, as
shown in Figure 4.7.
NOBLE CS DEPT 18
Unit II
Chapter 4 Utilizing Resource Media
<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 the integer array elements through a TextView. Since the integer array is
representing odd numbers, let’s change the resource ID of
the TextView in main.xml to oddnums_view.
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
NOBLE CS DEPT 19
Unit II
Chapter 4 Utilizing Resource Media
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>
The code that we write in the activity file StringArrayAppActivity.java to access the elements
of the integer array and to display them via TextView is shown in Listing 4.20.
Listing 4.20. Code Written in the Java Activity File StringArrayAppActivity.java to Access
Array Elements
package com.androidunleashed.stringarrayapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class StringArrayAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_string_array_app);
TextViewoddNumsView = (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);
}
}
NOBLE CS DEPT 20
Unit II
Chapter 4 Utilizing Resource Media
NOBLE CS DEPT 21
Unit II
Chapter 4 Utilizing Resource Media
5. After we add images to the res/drawable folders, the gen folder is regenerated where
the R.java file resides.
6. The R.java file includes a reference to the newly added image and hence can be used in
the layout file or other Java code.
@drawable/image_filename
In Java code, the image can be referenced using the following syntax:
R.drawable.image_filename
To display the image, let’s add an ImageView control to the layout file. Write the code in the
layout file activity_disp_image_app.xml as shown in Listing 4.21.
<LinearLayoutxmlns: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>
android:src="@drawable/bintupic"
This statement loads the image bintupic.png, which we pasted into the res/drawable folder.
After the application is run, the image is displayed, as shown in the Figure 4.9.
NOBLE CS DEPT 22
Unit II
Chapter 4 Utilizing Resource Media
Figure 4.9. The image displayed through an ImageView control using a drawable resource
We can also specify the image for the ImageView control through Java code.
To try this, let’s remove the reference to the bintupic image in the ImageView control
that we made through the src attribute.
Let’s write the code in the Java activity file DispImageAppActivity.java to assign an
image to the ImageView control as shown in Listing 4.23.
Listing 4.23. The Java Activity File DispImageAppActivity.java
package com.androidunleashed.dispimageapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
public class DispImageAppActivity extends Activity {
@Override
public 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);
}
}
NOBLE CS DEPT 23
Unit II
Chapter 4 Utilizing Resource Media
gets the ImageView control from the layout file and stores it in an ImageView object
called image.
image.setImageResource(R.drawable.bintupic);
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 the same output as shown previously in Figure 4.9.
The ToggleButton toggles between the two states, something like a radio button.
A ToggleButton can only be in one state out of two mutually exclusive states,for
example, On and Off.
To display a ToggleButton, we use the <ToggleButton> tag in the layout file.
To set the text for the button, the two attributes android:textOn and android:textOff are
used.
The default values for the two attributes are ON and OFF, respectively.
The following code shows how to create a toggle button using the ToggleButton tag:
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Play"
android:textOff="Stop" />
This code block defines a toggle button that shows the text Play in the On state and
shows Stop in the Off state.
NOBLE CS DEPT 24
Unit II
Chapter 4 Utilizing Resource Media
<LinearLayoutxmlns: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"/>
<ToggleButtonandroid:id="@+id/playstop_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Play"
android:textOff="Stop"/>
</LinearLayout>
We can see that the TextView control is assigned the ID response and is set to display
the default text: Select the Play button.
The ToggleButton is assigned the ID playstop_btn and is set to display Play and Stop in
the On and Off states, respectively.
We want the text of the TextView control to change on the click of the ToggleButton.
To enable the ToggleButton to switch text via the TextView control when it is clicked,
we need to write some Java code in the ToggleButtonAppActivity.java file as shown
in Listing 4.25.
Listing 4.25. Code Written in the Java Activity File ToggleButtonAppActivity.java
package com.androidunleashed.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 TextViewresp = (TextView)this.findViewById(R.id.response);
final ToggleButtonplayStopButton = (ToggleButton)
findViewById(R.id.playstop_btn);
playStopButton.setChecked(true);
NOBLE CS DEPT 25
Unit II
Chapter 4 Utilizing Resource Media
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");
}
}
});
}
}
After the application is run, we get the output shown in Figure 4.10 (left).
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 ToggleButton is selected, its caption changes to Stop, and the text in
the TextView changes to Play button is toggled to Stop button, as shown in Figure
4.10 (middle).
When the ToggleButton is selecte again, the caption in the ToggleButton changes back
to Play, and the text in the TextView control changes to Stop button is toggled to Play
button, as shown in Figure 4.10 (right).
That is, the caption in the ToggleButton, as well as the text in the TextView controls,
changes on every click of the ToggleButton.
NOBLE CS DEPT 26
Unit II
Chapter 4 Utilizing Resource Media
Gravity Control:
The following statement centrally aligns the text in the TextView control:
android:gravity="center"
android:layout_gravity="center"
Background image:
We can also add a background image to the ToggleButton by adding
the android:background attribute to the <ToggleButton> tag in the layout file.
The following statement sets the ic_launcher.png image as the background image of
the ToggleButton:
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.
NOBLE CS DEPT 27
Unit II
Chapter 4 Utilizing Resource Media
Only the statements in bold are newly added code; the rest of the code is the same as we saw
in Listing 4.25.
Listing 4.26. Code in the Java Activity File ToggleButtonAppActivity.java
package com.androidunleashed.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 TextViewresp = (TextView)this.findViewById(R.id.response);
final ToggleButtonplaystopbutton = (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.stop));
resp.setText("Play button is toggled to Stop button");
}
}
});
}
}
These statements prevent the default text from appearing on the ToggleButton in
its On and Off states. Now we replace the ic_launcher.png image with the play.png image by
setting the following attribute:
android:background="@drawable/play"
NOBLE CS DEPT 28
Unit II
Chapter 4 Utilizing Resource Media
This attribute displays the play.png image on application startup. The layout file main.xml on
applying these changes appears as shown in Listing 4.27.
Listing 4.27. Code Written in the Layout File main.xml
After the application is run, we find the play.png image appears in the ToggleButton (see Figure
4.12—left). After we select the Play button, the stop.png image appears to represent
the ToggleButton’s Off state. Figure 4.12 (middle and right) shows how the text displays when
the TextView changes after clicking the ToggleButton.
Figure 4.12. (left) The ToggleButton with a background image (no text) and the TextView on
application startup, (middle) the background image of ToggleButton and TextView changes on
selecting the ToggleButton, and (right) the original background image reappears on
the ToggleButton on clicking the ToggleButton again.
NOBLE CS DEPT 29