Unit - Ii Basic Widgets Understanding Role of Android Application Components
Unit - Ii Basic Widgets Understanding Role of Android Application Components
Unit - Ii Basic Widgets Understanding Role of Android Application Components
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.
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.
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.
<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.
<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.
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
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.
<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.
<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>
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);
}
});
}
}
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.
<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
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.
<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);
}
};
}