Unit - Ii Basic Widgets Understanding Role of Android Application Components

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

IV.

BTECH I-SEM, CSE: MOBILE APPLICATION DEVELOPMENT


UNIT - II
BASIC WIDGETS
Understanding Role of Android Application Components:
 Let’s start by creating an application that prompts the user to enter name and display welcome
message in return.
 To create application, open eclipse and choose, file, new android application project or click
android project creator icon on eclipse toolbar.

 In the Application Name box, enter the name of the Android project. Let’s name the application
WelcomeMsg. The project Name is automatically assigned, which is the same as the application
name by default. The Package Name is com.androidunleashed.welcomemsg.
 From the Build SDK drop-down, select Android 4.1 (API 16) as the target platform as we expect it
to be the version commonly used by your target audience.
 Select API 8: Android 2.2 (Froyo) from the Minimum Required SDK drop-down to indicate that the
application requires at least API level 8 to run.
 Select Create project in Workspace check box and Create custom launcher icon check box for new
project. Click the Next button to move to the next dialog box.
 Next dialog is Configure Launcher Icon, which is meant for configuring the icon for the application.
Keeping all default options in the dialog box, click the Next button to move further.
 Next dialog prompts us to select whether we want to create an activity. To create BlankActiity,
Select Create Activity check box and the BlankAcitivity option from the list and then click next.
 The next dialog asks us to enter information about the newly created activity. Name the activity
WelcomeMsgActivity.
 The layout filename and title name automatically change to reflect the newly assigned activity name.
Click the Finish button after supplying the required information.
 The application is created by ADT, along with all the necessary files.

P.SEKHAR
Understanding the Utility of Android API:
 The android platform provides a framework API that applications can use to interact with the
underlying Android system. The framework API consists of a core set of packages and classes;
 XML elements for declaring layouts, resources, and so on; a manifest file to configure applications;
intents; and much more.
 Framework API is specified through an integer called API level, and each Android platform version
supports exactly one API level, although backward compatibility is there; that is, earlier API levels
are supported.
 The initial release of the Android platform provided API Level 1, and subsequent releases have
incremented the API level. List of API levels shown below
Version Number API Level Code Name
Android 4.1 16 Jelly bean
Android 4.0.3 15 Ice cream Sandwich
Android 4.0 14 Ice cream Sandwich
Android 3.2 13 Honey comb
Android 3.1 12 Honey comb
Android 3.0 11 Honey comb
Android 2.3.3 10 Ginger bread
Android 2.3.1 9 Ginger bread
Android 2.2 8 Froyo
Android 2.1 7 Eclair
Android 2.0.1 6 Eclair
Android 2.0 5 Eclair
Android 1.6 4 Donut
Android 1.5 3 Cup cake
Android 1.1 2
Android 1.0 1

 Remember that to enable applications to run on a maximum number of platforms, you can set the
applications to target the lowest platform, Android 1.0.
 Because of backward compatibility, the application that supports the Android 1.0 platform can easily
run on all the devices, even on devices with the Android 4.0 platform. Opposite is not true.
 After creating the new Android application by name, WelcomeMsg, the ADT creates a
WelcomeMsg directory in the default Eclipse workspace for the project.
 It also creates subdirectories for keeping source files, compiled or generated files, resource files,
and so on.
 Several files, such as AndroidManifest.xml and project.properties are also automatically created to
make the job of configuring the Android application.
 You can have a look at the files and directories created by ADT if you expand the project tree in the
Package Explorer window.

Overview of the Android Project Files:


 The list below is just an overview of the files and directories.
1. /src folder: The folder that contains the entire Java source file of the application. The folder
contains a directory structure corresponding to the package name supplied in the application.
The folder contains the project’s default package: com.androidunleashed.welcomemsg. On
expanding the package, you find the Activity of the application, the WelcomeMsgActivity.java
file, within it.
2. /src/com.androidunleashed.welcomemsg: Refers to the package name of the application. To
avoid any collision among the class names, variable names, and so on from other Android
application. each application has to be packed in a unique container.
3. /src/com.androidleashed.welcomemsg/WelcomeMsgActivity.java: The default Activity files
of the application. Recall that each application has at least one Activity that acts as the main
entry point to the application. The activity file is automatically defined as the default launch
Activity in the Android Manifest file.
4. /gen folder: Contains Java files generated by ADT on
compiling the application. The gen folder will come
into existence after compiling the application for the
first time. The folder contains an R.java file that
contains references for all the resources defined in the
res directory. It also contains a BuildCon- fig.java file
that is used to run code only in debug mode.
5. /gen/com.androidunleashed.welcomemsg/R.java:
All the layout and other resource information that is
coded in the XML files is converted into Java source
code and placed in the R.java file. The R.java file is
compiled into the java byte code files and then
converted into .dex format. You should never edit this
file by hand.
6. Android SDK jar file: The jar file for the target
platform.
7. /assets folder: The assets folder is empty by default. It stores raw asset files that may be
required in the application. It may contain fonts, external JAR files, and so on to be used in the
application. The assets folder is like a resource folder where uncompiled resources of the project
are kept.
8. /bin folder: The folder that stores the compiled version of the application.
9. /res folder: The folder where all application resources (images, layout files, and string files) are
kept. Create a respective resource in the res folder is better than hard coding image or string.
You can change image or string or any other resource any time without disturbing code. Each
resource is assigned a unique resource ID, which automatically appears in the R.java file. To
categorize and arrange the resources, three subdirectories are created by default: drawable,
layout and values.
10. /res/drawable-xhdpi, /res/drawable/hdpi, /res/drawable-mdpi, /res/drawable-ldpi: applica-
tion’s icon and graphic resources are kept in these folders. Because devices have screens of
different densities, the graphics of different resolutions are kept in these folders .Usually
graphics of 320dpi, 240dpi, 160dpi and 120dpi are stored in the res/drawable-xhdpi, res/
drawable-hdpi/, res/drawable-mdpi , and res/drawable-ldpi folders, respectively. Application
picks up the graphic based on density of device.
11. /res/layout: Stores the layout file(s) in XML format.
12. /res/values: Stores all the values resources include many types such as string resource ,
dimension resource and color resource.
13. /res/layout/activity_welcome_msg.xml: The file used by WelcomeMsgActivity to draw views
on the screen. The views or controls are laid in the specified layout.
14. AndroidManifest.xml: The central configuration files for the application.
15. Proguard.cfg: Defines how proGuard optimizes the application code. ProGuard is a tool that
removes unused code from the Android application and optimizes it, which increases
performance.
16. Project.properties: Build file used by Eclipse and the Android ADT plug-in. It contains project
settings such as the build target. You can use this file to change various properties of the project
with editors available in Eclipse.
 Other folders include bin, libs and reference libraries are part of application. The bin folder is
hidden. The libs and referenced libraries folders don’t appear until a third party library and reference
are added to the project.
 The default content of the Activity file WelcomeMsgActivity. java is shown below
Package com.androidunleashed.welcomemsg;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class WelcomeMsgActivity extends Activity {
@Override
Public void onCreate(Bundle savedInstanceState)
{ Super.onCreate(savedInstanceState);
setContentview(R.layout.activity_welcome_msg);
}
@Overrride
Public Boolean onCreateOptionsMenu (Menu menu)
{ getMenuInflater().inflate(R.menu.activity_welcome_msg,
menu); return true;
}
}

Understanding Activities:
 Every unique screen user interacts with in an application is displayed through an Activity. Simple
application may consist of just one Activity, where as large application contains several Activities.
 A stack of Activities is maintained while running an application and activity at top of the stack is
one currently being displayed. When the back button is pressed, the Activity is popped from stack.
 The transition from one Activity to another is accomplished through the use of asynchronous
messages called intents. Intents can be use to pass data from one Activity to another.
 All the activities in the application must be defined in the Application’s manifests life. Each Activity
in an Android application is either a direct subclass of the Activity base class or a subclass of an
Activity subclass.

Understanding Android Activity Life Cycle:


 The Android Activity life cycle defines the states
or events that an Activity goes through from the
time it is created until it finishes running.
 Activity monitors and reacts to these events by
executing methods that override Activity class for
each event.
 Lists the methods executed during the different
events that occur during an android Activity life
cycle shown below.
METHOD DESCRIPTION
The method called when the Activity is first created. It initializes the value
onCreate() and is used to create the views of the application, open persistent data files
required by the Activity and so on.
The method called just before the Activity becomes visible on the screen. An
Activity can be either in a foreground or background state. When an Activity
onStart()
switches to the background state, the onStop() method is executed and when
it switches to foreground, the onResume() method is invoked.
The method called whenever the Activity becomes the foreground Activity,
whether it is right after the execution of the onStart() method or when some
onResume() other foreground Activity exits and the Activity appears at the top of the
Activity stack. A foreground Activity interacts with the user, i.e. receives
keyboard and touch inputs and generates the response.
The method called when the Activity is stopped and no longer is visible in the
foreground and some other Activity is switched to the foreground. This
onPause() method contains commands to minimize consumption of resources and to
store the Activity state, which will be used when the Activity resumes to the
foreground.
The method called when the Activity is no longer visible, either because
onStop() another Activity is switched to the foreground or because the Activity is
being destroyed.
The method called used when the Activity is completed and is about to get
onDestroy() destroyed. The system may simply terminate the process. You can use this
method to release the resources consumed by the Activity.

 All the activities of an application, permission and intents are defined through the XML-
structured manifest file AndroidManifest.xml. in this file all the different components of the
application are defined.

Role of the Android Manifest File:


 The configuration file AndroidManifest.xml is created by ADT when creating a new Android
project and is kept in the project’s root directory.
 Xml file that defines the overall structure and information about the application and It also contains
the information required in building and packaging the application for installing and deploying it on
an Android device or the emulator.
 It defines meta data of application such as its icons and label. Manifest file for the application that
you just created shown below.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com. androidunleashed.welcomemsg "
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=".WelcomeMsgActivity"
android:label= "@string/title_activity_welcome_msg”>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

 The <manifest> tag, is the root element of this XML document and contains several attributes:
1. Android: Identifies the andriod namespace used to provide several system attributes used within
the application.
2. package: Its value is set to the application's Java Package. The name of the application package
acts as the unique identifier for the application in the Android device.
3. versionCode/versionName: The Version Code attribute is used to define the current application
version. The versionName attribute is used to specify a version number that is displayed to users.
4. <uses-sdk>: This tag is optional and is used to specify the Maximum, Minimum and preferred
API level required for the application to operate. Three attributes are used with this tag as
follows:
 android:minSDKversion: Used to specify the minimum API level required for this
application to run. The default is"1". Minimum API level required by the application is 15.
the application cannot run on an API level lower than the one specified attribute
andriod:minSDKVersion="15".
 android:targetSDKversion: Used to specify the preferred API level on which the
application is designed to run.
 android:maxSDKversion: Used to specify the maximum API level supportable by the
application, the application cannot run on an API level higher than the one specified
attribute.
5. <application> tag: which is the parent of application controls tags. @string and @drawable
refer to the strings and drawable resources, respectively.
6. <activity> tag: which describes an Activity component. This tag's name attribute identifies a
class that is an Activity, welcomemsactivity. It relative to com.androidunleashed.welcomemsg
package.
7. <intent-filter>: The intents are used to interact with the applications and services. By default,
the intent specifies the action as MAIN and the category as LAUNCHER; that is, it makes
application launcher to launch when the application starts.

 the following are some of the most commonly used tags:


1. <service> tags: Used for declaring service. service refer to the process that run in the
background without a user interface.
2. <receiver> tags: Used for declaring broadcast receivers. Boardcast receivers are used to listen
and respond to broadcast announcements. An application can have any number of broadcast
receivers. A broadcast receiver responds by taking a specific action.
3. <provider> tags: Used for declaring content providers. They help in handling, storing, and
sharing data such as audio, images, video and contact lists with other applications..
4. <uses-permission> tags: Used for declaring the permission that the application
needs. Example:
<uses-permission android:name="android.permission.CAMERA"/>:
Used for the application that needs to use the camera.
<uses-permission android:name="android.permission.INTERNET"/>:
Used for the application that needs to access the internet.

Using the Manifest Editor:


 To manipulate androidmanifest.xml file use of the manifest editor in eclipse, right click the
androidmanifest.xml file in the package explorer window, and select open with android manifest
editor.
 Android Manifest overview screen shown below
 Screen provides user-friendly interface to configure application, enabling you to set application
version information and root-level manifest nodes, including uses-sdk and uses-permission.
 It provides shortcut links to the application, permissions, instrumentation and raw xml screens.

Creating the User Interface:


 There are three approaches to creating user interface in android. You can create user interface
entirely in java code or entirely in XML or in both.
 The XML file in which you create the user interface is activity_welcome_msg.xml found in the
res/layout folder. The default layout in which the controls or views are usually arranged is
RelativeLayout. it shown below

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@srting/hello_world"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:context=".WelcomeMsgActivity"/>
</RelativeLayout>

 You want to prompt the user to enter a name,and in return the application displays a welcome
message along with the entered name.
 To achieve above requirement you change activity_welcome_msg_.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click Me"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>

 In the preceding XML file, four controls are used: two TextViews, one EditText and one Button
Control. The first TextView prompts the user to enter a name by displaying the message Enter your
name: and the second TextView is used to display the Welcome message to the user.
 When the user selects the Button, control will display welcome message through the second
TextView control.
 The EditText, Button, and one of the TextView controls are assigned the IDs user_name, click_btn
and response, respectively. These IDs are used to access these controls in the java Activity file.

Commonly Used Layouts and Controls:


 The Views or the controls that we want to display in an application are arranged in an order or
sequence by placing them in the desired layout.
 Some of layouts as follows:

P.SEKHAR 10
1. LinearLayout: In this layout, all elements are arranged in a descending column from top to
bottom or left to right. Each element contains properties to specify how much of the screen space
it will consume.
2. RelativeLayout: In this layout, each child elements is laid out in relation to other child
elements. That is, child elements appear in the relation to the parent.
3. AbsoluteLayout: In this layout, each child is given a specific location within the bounds of the
parent layout object. This layout is not suitable for devices with different screen sizes.
4. FrameLayout: This is a layout used to display a single view. Views added to this are always
placed at the top left of the layout. Any other view that is added to the FrameLayout overlaps the
previous view.
5. TableLayout: In this layout, the screen is assumed to be divided into table and rows, and each
of the child elements is arranged in a specific row and column.
6. GridLayout: In this layout, child views are arranged in a grid format (in the rows and columns
pattern). The views can be placed at the specified row and column location. Also, more than one
view can be placed at the given row and column position.
 The following list highlights some of the controls commonly used in Android applications:
1. Textview: A read-only text label. It supports multiline display, string formatting automatic
word wrapping.
2. EditText: An editable text box that also accepts multiline entry and word-wrapping.
3. ListView: A ViewGroup that creates and manages a vertical list of views, displaying them as
rows within the list.
4. Spinner: A TextView and an associated list of items that allows us to select an item from the
list to display in the text box.
5. Button: A standard command button.
6. CheckBox: A button allowing a user to select (check) or unselect (uncheck).
7. RadioButton: A mutually exclusive button, which when selected, unselects all other buttons
in the group.

Event Handling:
 In our sample application, you want the user to enter a name in the EditText control. After the user
has entered the name and clicks the Button control, a welcome message displays on the screen.
 The action of clicking a Button, pressing the Enter Key, or performing any action on any control is
considered an event. The action to be taken when the event occurs is called event handling.
 To handle an event, you use the listeners that wait for an event occurrence. Event listener is an
interface in the view class that contains single callback method, called an event occurrence.
 An instance of the implementation is passed to the respective control through setOnClickListner( )
method.
 Event handling should be three ways:
1. Creating an anonymous inner class
2. Implementing the OnClickListener interface
3. Declaring the event handler in the XML definition of the control

Creating an Anonymous Inner Class:


 In this method of event handling, an anonymous class is defined with an OnClickListener interface,
and an onClick(View v) method is implemented in it.
 The anonymous inner class is passed to the listener through the setOnClickListener( ) method. To
implement the concept of anonymous inner class for event handling, the java activity file
WelcomeMsgActivity.java is modified to appear as shown below.

Package com.androidunleashed.welcomemsg;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
public class WelcomeMsgActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
Button b=(Button)this.findViewById(R.id.click_btn);
b.setOnClickListener(new Button.OnClickListener( ){
public void onClick(View v) {
TextView resp=(TextView) findViewById(R.id.response);
EditText name=(EditText) findViewById(R.id.user_name);
String str="welcome "+name.getText( ).toString( )+" ! ";
resp.setText(str);
}
});
}
}
 Listener is implemented inline through an anonymous class with an onClickListener interface. A
callback method onClick(View v) is implemented in the class, and, finally, the anonymous class is
associated with the Button object b.
 whenever the Button control is clicked in the application , the onClick( ) method, you fetch the
TextView and EditText controls defined in the layout file with the ID’s response and user_name,
and then map them to the TextView and EditText objects resp and name, respectively.
 The name entered by the user is prefixed with a Welcome message, is assigned to a string object,
str. Finally, the str object is assigned to The TextVew object, resp, to display the Welcome message,
along with the user’s name on the screen.

Running the Application:


 To run the application, you create an Eclipse launch configuration. If you run the application without
creating a launch configuration, you see the Run as dialog box shown below.
 Choose Android Application, and a launch configuration is
automatically created.
 The ADT compiles the application and then deploys it to the
emulator with the default launch configuration.
 The Android emulator is loaded showing the output of the
application. You can see in the emulator that a prompt
message Enter your name: appears via the TextView Control.
 A blank text box appears via the EditText Control where you
will enter name and button appears via Button Control.
 After you enter the user name Kelly and select the Click Me button, a welcome message,
Welcome Kelly!, appears via the TextView Control.
Activity Implementing the OnClickListener Interface:
 In this method of event handling, the Activity class implements the onClickListener interface, which
requires us to implement the onClick() method in this class.
 The onClick() method is declared inside the class and the listener is set by passing a reference to the
class by the following statement:b.setOnClikListener(this).
 To implement OnClickListener interface, the activity file WelcomeMsgAcivity.java is modified to
appear as shown below.
package com.androidunleashed.welcomemsg;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class WelcomeMsgActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
Button b = (Button) this.findViewById(R.id.click_btn);
b.setOnClickListener(this);
}
public void onClick(View v) {
TextView resp=(TextView) findViewById(R.id.response);
EditText name=(EditText) findViewById(R.id.user_name);
String str="welcome "+name.getText( ).toString( )+" ! ";
resp.setText(str);
}
}
 This code locates the Button Control that you created in the activity_welcome-msg.xml file (with the
ID click_btn), assigns it to the instance b, and attaches an event listener to it.
 When event occurs via a button click, the onClick() method is executed. TextView and EditText
controls of activity_Welcome_msg.xml are located and accessed via the resp and name objects.
 The username entered in the EditText control is fetched and displayed along with a welcome
messasge via the TextView Control.
Declaring the Event Handler in the XML Control Definition
 Since Android SDK 1.6, another way to set up a click handler for the Button Controls is there.In the
XML definition of a Button in the layout file activity_welcome_msg.xml,you can add an
android:onClick attribute.
 This attribute is used to represent the method you want to execute when a click event occurs via the
Button Control.
android:onClick="dispMessage"
All you need is to define the dispMessage () in the Activity class to perform the desired action.
 Remember, to try out this method of event handling, you need to modify the layout file
activity_welcome_msg.xml of the application is 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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click Me"
android:onClick="dispMessage"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>

 The attribute android:onClick means that the dispMessage() method must be invoked when the
button is clicked. You can declare the same event handler for several controls.
 In the Java Activity file WelcomeMsgActivity.java, the method dispMessage() is defined. This
method performs the task of accessing the name entered in the EditText control and displaying a
welcome message along with the entered name.
 Add method dispMessage(), Activity file WelcomeMsgActivity.java appears as shown in below.
package com.androidunleashed.welcomemsg;.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
public class WelcomeMsgActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
public void dispMessage(View v){
TextView resp=(TextView) findViewById(R.id.response);
EditText name=(EditText) findViewById(R.id.user_name);
String str = "Welcome " + name.getText().toString() + " ! ";
resp.setText(str);
}
}
 In dispMessage() method, TextView and EditText controls with Ids response and user_name are
accessed from the layout file, activity-welcome_msg.xml and mapped to the TextView and objects
resp and name, respectively.
 The username entered in EditText control is accessed through the name object (EditText control)
and is designed to the resp object (TextView Control) along with welcome message for display.
 Define same event handler method more than one button control with help of view object. In event
handler, the getid() method of the view object can be used to discover the button from which the
event has occurred and an appropriate action can be taken, as shown below:
public void dispMessage (view v) {
if (v.getId()==R.id.id1) { }
if (v.getId()==R.id.id2) { }
......
}
 id1 and id2 are the IDs of the button controls that declare the same event handler.
Displaying Messages through Toast:
 A Toast is a transient message that automatically disappears after a while without user interaction. It
is used to inform the user about happenings that are not very important
 A Toast is created by calling the static method, makeText (), of the Toast class. The syntax of the
makeText () method is shown below:
Toast.makeText (Activity_context, string_to_display, duration)
 The method needs the Activity (Context) String to display, as well as the duration for which the
message is displayed on the screen. You can also supply the ID of the String resource that you want
to display.
 The duration is expressed in the form of constants, such as Toast.LENGTH_SHORT or
Toast.LENGTH_LONG, to determine the duration for which the string’s message remains on the
screen.
 You call the show() method on the returned Toast instance to display the containing string or
message.
 To display the welcome message through Toast, modify the java activity file WelcomeMsg
Activity.java as shown below.

pacage com.androidunleashed.Welcomemsg;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
public class WelcomeMsgActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_msg);
}
public void dispMessage(View v) {
EditText name=(EditText) findViewById(R.id.user_name);
String str="welcome "+name.getText( ).toString( )+" ! ";
Toast.makeText (WelcomeMsgActivity.this, str, Toast.LENGTH_SHORT) .show () ;
}
}
 You can see that a String object, str, is defined, which contains a welcome message and the name
entered by the user in the EditText control with the ID user_name.
 The text in the string object, str, is displayed via Toast, as shown in below. Toast is transient, it is
not visible for an extensive period, and you don’t receive any confirmation that the user actually saw
it.
 Therefore, we continue to use the TextView control in Android application to display information to
the user.

Creating and String an Activity:


 The structure that is used to start, stop, and transaction between Activities within an application is
called Intent.

Describing Operations through Intent:


 Intent is a data structure; It consists of an action that the application needs to perform, data to
operate on, and other information helpful in executing the operation.
 Intent can be explicit or implicit as follows:
 Explicit Intent-In an explicit intent, you specify the Activity required to respond to the intent;
that is, you explicitly designate the target components. Because your application, an explicit
intent is limited to be used within an application
 Implicit Intent-In an implicit intent you just declare intent and leave it to the platform to find an
Activity that can respond to the intent. It is the job of the Android platform to search for the
most suitable component to handle the implicit intent.
Method to start an activity:
 The method used to start an activity is startActivity(). First create an implicit or explicit intent object
and pass it to the startActivity() method in the format here:
startActivity (my_intent) ;
Where my_intent passed as a parameter to startActivity(). The startActivity() method find and starts
the single Activity that best matches the given intent.
 To explicit specify the Activity that you want to start through an intent, create a new intent
specifying the current application context and class name of the activity you want to launch and pass
this Intent to the startActivity () method,as shown here:
startActivity (new Intent (this, welcome.class));
 If startActivity() is unable to find the specified activity, an android.content.ActivityNotFound
Exception is thrown.
 Let’s explore the concept, You create an application similar to the WelcomeMsg application but
with the following two differences:
 Instead of using the default Activity automatically created by the ADT, you create your own
Activity in this application.
 You create and use your own layout file instead of the default layout file.
 Launch Eclipse and create a new Android Project called welcomeApp with the following settings:
 Select Android 4.1 as the Target Platform.
 Let the application name be the default, which is welcomeApp.
 Let the package name be com.androidunleashed.welcomeapp.
 Let the Activity name be the default, which is welcomeAppActivity.

Creating your own Layout File:


 To create a new layout file, from the Package Explorer window, right click the res/layout folder and
select the New, Android XML File option.
 A dialog box appears asking for information about the new Android XML File. In the File text box,
enter the filename as welcome. Select the option linear layout from the Root Element and finally,
select the Finish button.
 The layout file, welcome.xml, is created in the res/layout folder. The initial content of the file is
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">
</LinearLayout>
 add two TextView controls, an EditText and a Button control, to the layout file. After you add these
controls, the contents of the welcome.xml file will be 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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name:"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/click_btn"
android:text="Click Me"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>

Creating a New Activity:


 You know that an Activity file is in the form of a java file. So, you need to add a java file to the
package com.androidunleashed.welcomeapp that’s inside the src folder of the application.
 To create an Activity, right-click the package com.androidunleashed.welcomeapp and select the
New, class option.
 A New Java Class dialog box appears, requesting you to enter the name of the Java file. Finally,
Select the Finish button to create the Java file.
 The Activity welcome.java is added to the package with the default content, as shown here:
Package.com.androidunleashed.welcomeapp;
Public class Welcome {
}

P.SEKHAR 20
 Let’s add some action to the Activity file. Recall that this application is similar to the WelcomeMsg
application. it prompts the user to enter a name and prints a welcome message when the Button
control is selected.

Package com.androidunleashed.welcomeapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
public class Welcome extends Activity{
@override
Protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.welcome);
Button b= (Button)this.findViewById (R.id.click_btn);
b.setOnClickListener (new Button.OnClickListener(){
public void onClick(View v){
TextView resp= (TextView)findViewById(R.id.response);
EditText name= (EditText)findViewById(R.id.user_name);
String str= “welcome “+name.getText().toString()+” !”;
resp.setText(str);
}
});
}
}

Registering the New Activity:


 Only the components declared in the application’s manifest file AndroidManifest.xml are visible to
Android and hence can be used to run the application.
 So, new Activity Welcome.java must be declared in the AndroidManifest.xml file to make it visible
to Android and start it.after adding new activity AndroidManifest.xml file is modified as shown
below
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com. androidunleashed.welcomemsg "
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=".WelcomeMsgActivity"
android:label= "@string/title_activity_welcome_app”>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Welcome" android:label="@string/app_name"/>
</application>
</manifest>

Starting the Activity:


 After registering the Activity welcome.java in the AndroidManifest.xml file, you can now start it by
using the startActivity() method.
 This startActivity() method is the default Activity file WelcomeAppActivity.java for start, after
adding the startActivity() method, appears as shown below.

package com.androidunleashed.welcomeapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
public class WelcomeAppActivity extends Activity{
@override
Public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_app);
startActivity(new Intent(this, Welcome.class));
}
}
 The startActivity() method creates an explicit intent, which explicitly specifies that the Activity file
Welcome.java is to be run at the start.
 When the application is run, you see the same output as that of the WelcomeMsg application.

Using the EditText Control:


 The EditText control is a subclass of TextView and is used for getting input from the user. You can
use several attributes to configure the EditText control to suit your requirements.
 The default behaviour of EditText control to remain on a single line only and let the text scroll to the
left.
 You can also hide the characters typed by the user for security purposes, that is, convert the
characters into dots, which you usually see while typing passwords.
Example:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"
android:text="Enter your name:"
android:singleLine="false"/>
 The preceding example sets the EditText control to expand to multiple lines when the user types
beyond the width of the control. The control displays the hint text Enter your name, which is
automatically erased as the user types data.

Attributes Used to Configure the EditText Control:


 The following is a list of attributes that can be used to configure the EditText control:
1. android: layout_width :
 Used to set the width of the EditText control. The two valid values are wrap_content and
match_parent. The value wrap_content sets the width of the EditText control to accept only a
single character. When the user types text, the width of the EditText control automatically
increases to accommodate the new content. Also, the cursor moves to the next line when the
boundary of the container is reached.
 No text scrolling takes place unless the android: scrollHorizontally attribute is set to “true”. In
this case, instead of moving to the next line, the text scrolls left to accommodate the newly
typed content.
 If the value of the android: layout_width attribute is set to match_parent, the width of the
EditText control is set equal to the width of its container. When the user types the text beyond
the available width, the cursor moves to the next line.
2. android: layout_height :
 Used to set the height of the EditText control. Valid values are wrap_content and
match_parent. When the value wrap_content is assigned to the control, the height of the
EditText control increases when typing text beyond the width of the control.
 If the value match_parent is assigned to the control, text expands the height of the control to
fill up the height of the container.
3. android: singleLine
 When set to true, forces the EditText control to remain on a single line. That is, on reaching the
end of the available width, the text that is typed in scrolls to the left. I
 if the value is set to false, the cursor moves to the next line when the end of the available width
of the control is reached.
4. android: hint
 Displays helpful text in the EditText control to guide user entry. The text automatically
disappears when the user enters data. For example, android: hint=”Enter your name”.
5. android: lines
 Sets the height of the EditText control to accommodate the specified number of lines. For
example, android: lines=”5”. Typing text beyond the fifth line causes the text to scroll up .
6. android: textSize
 Sets the size of the text typed in the EditText control. You can specify the size in any of the
following units of measurement: px, in, mm, pts, dip, and sp. For example, android:
textSize=”15px”.
7. android: autoText
 When set to true enables the EditText control to correct common spelling mistakes.
8. android: capitalize
 Automatically converts typed text into capital letters. The valid values are none, characters,
words and sentences.
 The value none does not capitalize anything. The value character capitalizes every character.
The value words capitalize the first character of every word. The value sentences capitalize the
first character of the first word of each sentence.
9. android: password
 When set to true, the attribute converts the typed characters into dots to hide entered text.
10. android: minWidth
 Used to specify the minimum width of the control.
11. android: maxWidth
 Used to specify the maximum width of the control. Text typed beyond the maximum width
scrolls if the android: scrollHorizontally attribute is set to true; otherwise, it moves onto the
next line.
12. android: minHeight
 Used to specify the minimum height of the control.
13. android: maxHeight
 Used to specify the maximum height of the control.
14. android: scrollHorizontally
 When set to true, makes the text scroll horizontally if typed beyond the specified width of the
control.
15. android: inputType
 Specifies the type of data that will be typed in the EditText control. This attribute configures
the onscreen keyboard too.
 There are many possible values that include number, phone, text, textCapCharacter,
textMultiLine and textPassword. shows as android: password, android: singleLine, android:
numeric, android: phoneNumber, android:capitalize and android:autoTexta

Adding an Event Listener to the EditText Control:


 You learn how to add an event listener to the EditText control that checks for the occurrence of an
event in the EditText control and executes the callback method.
 In this application, an EditText control is displayed on the screen asking the user to enter a name.
After the user enters a name and presses the Enter key, a welcome message displays via the
TextView control.
 First launch Eclipse and create a new Android project called EditTextApp, and modify
activity_edit_text_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">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/user_name"
android:text="Enter your name:"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"/>
</LinearLayout>
 You can see that the layout contains two controls: EditText for getting the name from the user and
TextView for displaying a welcome message. The EditText and TextView controls are assigned the
user_name and response IDS, respectively.
 To add an action, that is, to display the welcome message when the user presses the Enter key after
entering a name, we need to write code in the Activity file EditTextAppActivity.java shown below

Package.com.androidunleashed.edittextapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.KeyEvent;
public class EditTextAppActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_text_app);
final TextView resp= (TextView) this.findViewById (R.id.response);
final EditText username=(EditText) findViewById(R.id.user_name);
username.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if((event.getAction()== KeyEvent.ACTION_UP) &&
(keyCode==(KeyEvent.KEYCODE_ENTER))){
resp.setText("Welcome "+username.getText()+"!");
return true;
}
return false;
}
});
}
}
 EditText control from the layout is captured and mapped to the username EditTextobject.To display
the welcome message to the user, TheTextView control with the response ID is captured from the
layout and assigned to the TextView object resp.
 An event listener, OnKeyListener, is added to the EditText,object username so that the callback
method onkey() is invoked whenever a key is pressed. The onkey() method is implemented, it
checks whether the enter key is pressed.
 When the enter key is pressed, welcome message is displayed to the user through the TextView
object, resp. The onkey() method is set to return false until the enter key is pressed. The onkey()
method is set to return true when the enter key is pressed by the user.
 In output can see the hint text Enter your name in the Edit Text control. After the user has entered
name and pressed the enter key, the username and the welcome message appear, as shown below

Choosing Options with ChekBox:


 A checkbox control has two states: checked and unchecked. When the checkbox is selected, it
toggles its state from checked to unchecked and vice versa
 .A checkbox is created via an instance of android.widget.CheckBox. in java, the following methods
can be used with CheckBox controls:
1. isChecked() - Determines whether the chechbox is checked.
2. setChecked() - Sets or changes the state of the checkbox.
3. toggle() - Toggles state of the checkbox state from checked to unchecked or vice versa.
 To add an eventListener, you can implement the OnCheckedChangeListener interface that invokes
the callback method onCheckedChanged() when the state of the checkbox changes.
 In addition, you can also use the traditional implementation the onClickListener interface, that
invokes the onClick() method when any of the CheckBox controls are clicked.
Example:
<Checkbox android:id=”@+id/purchase”
android:layout_height=”wrap_content”
android:layout_width=”match_parent”
android:text=”purchase”/>
 To learn concept of CheckBox. Let’s create an Android application based on these controls. Each
representing food item along with its price. When food items are selected, total price is displayed.
 The application shows us how checkbox controls are displayed, how event Listener is attached to
them, and whether the checkbox is in a checked or unchecked state.
 Launch Eclipse, create a new Android project called CheckBoxApp, and add three checkbox
controls to the Activity Layout file activity_check_box_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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Items you Want"/>
<CheckBox
android:id="@+id/checkbox_pizza"
android:layout_height="wrap_content"
android:text="pizza $15"
android:layout_width="match_parent"/>
<CheckBox
android:id="@+id/checkbox_hotdog"
android:layout_height="wrap_content"
android:text="Hot Dog $5"
android:layout_width="match_parent"/>
<CheckBox
android:id="@+id/checkbox_burger"
android:layout_height="wrap_content"
android:text="Burger $10"
android:layout_width="match_parent"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bill_btn"
android:text="Calculate Bill"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/amount"/>
</LinearLayout>
 You can see that two TextViews, three CheckBoxes and a Button control. The first TextView is for
displaying a message, Select Items you want, asking the user to select the food items using the
CheckBoxControls.
 The three CheckBoxes are assigned unique ID’s — checkbox_pizza, checkbox_hotdog and
checkbox_burger — and they represent the food items, Pizza, HotDog and Burger respectively. The
caption and ID assigned to the button control are bill_btn and Calculate Bill respectively.
 The second Text View is assigned the ID amount and is meant for displaying the totak price of the
food items selected by the user.
 To add an action to the application, that is, to check the status of each of the checkbox controls and
to print the sum of the food items selected, You need to write some Java code in the activity file
shown below

package com.androidunleashed.checkboxapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.CheckBox;
import android.view.View;
import android.view.View.OnClickListener;
public class CheckBoxAppActivity extends Activity implements OnClickListener{
CheckBox c1,c2,c3;
TextView resp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box_app);
Button b=(Button)this.findViewById(R.id.bill_btn);
resp=(TextView)this.findViewById(R.id.amount);
c1=(CheckBox)this.findViewById(R.id.checkbox_pizza);
c2=(CheckBox)this.findViewById(R.id.checkbox_hotdog);
c3=(CheckBox)this.findViewById(R.id.checkbox_burger);
b.setOnClickListener(this);
}
public void onClick(View v){
int amt=0;
if(c1.isChecked()){
amt=amt+15;
}
if(c2.isChecked()){
amt=amt+5;
}
if(c3.isChecked()){
amt=amt+10;
}
resp.setText("Bill is"+Integer.toString(amt));
}
}

 The Button control with the ID bill_btn is accessed from the layout file and is mapped to the Button
object b. The TextView control with the ID amount is accessed from the layout file is mapped to the
TextView object resp.
 Three CheckBoxes with the IDs checkbox_pizza, checkbox_hotdog, and checkbox_burger are
accessed from the layout file and mapped to the CheckBox objects c1,c2 and c3 respectively.
 An event handler, setOnClickListener is attached to the button. Hence, whenever the button is
clicked, the OnClick() method is called. In the OnClick() method, an integer variable amt is
initialized to 0.
 The state of each check box is checked through the isChecked() method. The isChecked() method
returns the Boolean value true if the check box is checked; otherwise, it returns false. The three
check boxes represent the food items Pizza, HotDog and Burger, respectively.

P.SEKHAR 30
 if any of them is selected, the amount associated with that food item is added to the amt variable.
The total in the amt variable is displayed on the screen by assigning it to the TextView object resp.
 When application is run, you get below Screens.

Choosing Mutually Exclusive Items Using RadioButtons


 RadioButton controls are two-state widgets that can be in either a checked or unchecked state. The
difference between check boxes and radio buttons is that you can select more that one check box in a
set, whereas radiobuttons are mutually exclusive-only one radio button can be selected in a group.
 To make them mutually exclusive, RadioButton controls are grouped together into the RadioGroup
element so that no more than one can be selected at a time.
 To create a group of radio buttons, first create a RadioGroup and then populate the group with few
RadioButtoncontrols, as shown in the following example:
<RadioGroup
android:id=”@+id/group_hotel”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”>
<RadioButtonandroid:id=”@+id/radio_fivestar”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Five Star”/>
<RadioButtonandroid:id=”@+id/radio_threestar”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Three Star”/>
</RadioGroup>
 In the preceding code block, RadioGroup with the group_hotel ID is defined, which contains two
RadioButton controls with the IDs radio_fivestar and radio_threestar, respectively. Because only a
single radio button in a group can be in a checked state.
 In Java, the following methods can be applied to RadioButtons:
1. isChecked() - Detects whether the RadioButton contrl is selected.
2. toggle() - Toggles the state of the RadioButton from selected to unselected and vice versa.
3. check() - Checks a specific RadioButton whose ID is supplied in the method.
4. getCheckedRadioButtonId() - Gets the ID of the currently selected RadioButton control. It
returns –1 if no RadioButton control is checked.
 Let’s create an application using the concept of radio buttons. In this application, you define two
RadioButton controls in a RadioGroup. Each RadioButton represents a hotel type, and whenever a
RadioButton is selected, the hotel type represented by it will be displayed through a TextView
control.
 Launch Eclipse,create a new Android project called RadioButtonApp, and add two RadioButton
controls to the Activity layout file activty_radio_button_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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of hotel"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_fivestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Five Star"/>
<RadioButton
android:id="@+id/radio_threestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three Star"/>
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hoteltype"/>
</LinearLayout>
 you can see that two RadioButton controls with thradio_fivestar and radio_threestar IDs are grouped
inside a RadioGroup. This means that the two radio buttons have become mutually exclusive.
 To add an event listener action to the two RadioButton controls, you need to write some Java code in
the Activity file( RadioButtonAppActivty.java) shown below.

packagecom.androidunleashed.radiobutttonapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.RadioButton;
import android.view.View;
import android.view.View.OnClickListener;
public class RadioButtonAppActivty extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_radio_button_app);
RadioButton radioFivestar=(RadioButton)findViewById(R.id.radio_fivestar);
RadioButton radioThreestar=(RadioButton)findViewById(R.id.radio_threestar);
radioFivestar.setOnClickListener(radioListener);
radioThreestar.setOnClickListener(radioListener);
}
private OnClickListener radioListener=new OnClickListener(){
public void onClick(View v){
TextView selectedHotel=(TextView)findViewById(R.id.hoteltype);
RadioButton rb=(RadioButton) v;
selectedHotel.setText("The hotel type selected is:" + rb.getText());
}
};
}
 The two RadioButton controls are captured from the layout and mapped to the RadioButton objects
radioFivestar and radioThreestar.
 The View.OnClickListener interface is implemented to listen to the click events on the RadioButton
controls. The onClick() callback method is implemented. This is the method that is executed when
any of the RadioButton controls are selected.
 In the onClick() callback method, the TextView control from the layout is captured and mapped to
the TextView object selctedHotel.
 The text content of the RadioButton control that is selected by the user is fetched through the
getText() method and is displayed through the Textview object selected-Hotel.
 On execution of the application, you see two RadioButton controls on the startup screen, as shown
below. When the user selects the five star RadioButton, the TextView displays the message “The
hotel type selected is: Five Star” .
 When the user selects the threestar RadioButton, the Textview displays the message “The hotel type
selected is: Three Star”.

 Similarly, the other RadioGroup that represents room types will have three RadioButton controls to
show three options: Ordinary Room, Luxury Room, and Grand Suite.
 Add radiogroup control to preceding application. The layout file with two RadioGroup controls
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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of hotel"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_fivestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Five Star"/>
<RadioButton
android:id="@+id/radio_threestar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Three Star"/>
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hoteltype"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select the type of room"/>
<RadioGroup
android:id="@+id/group_room"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radio_suite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Grand Suite"/>
<RadioButton
android:id="@+id/radio_luxury"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Luxury Room"/>
<RadioButton
android:id="@+id/radio_ordinary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ordinary Room"/>
</RadioGroup>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/roomtype" />
</LinearLayout>

 To make two independent sets of radio buttons, one to represent hotel types and another to represent
room types, you create two RadioGroup controls with the group_hotel and group_room IDs.
 First RadioGroup, group_hotel, contains two RadioButton controls with the radio_fivestar and
radio_threestar IDs to represent five star and three star hotels.
 Similarly, the next RadioGroup, group_room, contains three RadioButton controls with the
radio_suite, radio_luxury , and radio_ordinary IDs to represent the suite, luxury, and ordinary room
types.
 The two TextView controls are used to display the messages select the type of hotel and select the
type of room, asking the user to select the type of hotel and room.
 The third TextView with the hoteltype ID is used to display the options selected by the user. To
make the two RadioGroups functional and to display the hotel and room type selected by the user,
write the code shown below in the Java activity file RadioButtonAppActivity.java.

Package com.androidunleashed.radiobuttonapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.RadioButton;
import android.view.View;
import android.view.View.OnClickListener;
public class RadioButtonAppActivity extends Activity{
String str1=" ";
String str2=" ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_button_app);
RadioButton radioFivestar = (RadioButton) findViewById(R.id.radio_fivestar);
RadioButton radioThreestar=(RadioButton) findViewById(R.id.radio_threestar);
RadioButton radioSuite = (RadioButton) findViewById(R.id.radio_suite);
RadioButton radioLuxury = (RadioButton) findViewById(R.id.radio_luxury);
RadioButton radioOrdinary = (RadioButton) findViewById(R.id.radio_ordinary);
radioFivestar.setOnClickListener(radioListener1);
radioThreestar.setOnClickListener(radioListener1);
radioSuite.setOnClickListener(radioListener2);
radioLuxury.setOnClickListener(radioListener2);
radioOrdinary.setOnClickListener(radioListener2);
}
private OnClickListener radioListener1 = new OnClickListener(){
public void onClick(View v) {
TextView selectedOptions = (TextView) findViewById(R.id.hoteltype);
RadioButton rb = (RadioButton) v;
str1 = "The hotel type selected is: " + rb.getText();
selectedOptions.setText(str1 + "\n" + str2);
}
};
private OnClickListener radioListener2 = new OnClickListener(){
public void onClick(View v){
TextView selectedOptions = (TextView) findViewById(R.id.hoteltype);
RadioButton rb = (RadioButton) v;
str2="Room type selected is: "+rb.getText();
selectedOptions.setText(str1+"\n"+str2);
}
};
}

 The RadioButton controls with IDs radio_fivestar, radio_threestar,radio_suite, radio_luxury and


radio_ordinary are captured from the layout file and mapped to the RadioButton objects
radioFivestar, radioThreestar, radioSuite, radioLuxury, and, radioOrdinary respectively.
 Two event listener interfaces are created, radioListener1 and radioListener2. One checks for event
occurrences in the RadioButton contols in group_hotel, and the other checks for the occurrence of
events in the RadioButton controls in group_room. Both the interfaces have the callback method
onClick () implemented in them.
 When any of the RadioButton controls in the first RadioGroup, group_hotel, is selected, the callback
method onClick() of radioListener1 is executed and text is assigned to the string str1 to represent the
RadioButton selected in that radio group.
 When any RadioButton control from the second RadioGroup, group_room is selected, the callback
method onClick() of radioListener2 is executed. This assigns text to the string str2 to represent the
RadioButton selected in that radio group.
 The TextView with the hotel_type ID is captured from the layout file and is mapped to the
TextView object selected Options. The text messages in both the str1 and str2 Strings are assigned to
the TextView control selectedOptions for display.
 On running the application, you see two sets of RadioButton controls in their respective
RadioGroups as shown below

You might also like