0% found this document useful (0 votes)
5 views35 pages

Unit Ii

Unit II of the Mobile Application Development course covers basic widgets and the role of Android application components, including activities, services, and content providers. It explains the Android API utility, project file structure, activity lifecycle, and the Android Manifest file's importance in application configuration. Additionally, it discusses user interface creation methods in Android applications.

Uploaded by

hareeshmajnu1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views35 pages

Unit Ii

Unit II of the Mobile Application Development course covers basic widgets and the role of Android application components, including activities, services, and content providers. It explains the Android API utility, project file structure, activity lifecycle, and the Android Manifest file's importance in application configuration. Additionally, it discusses user interface creation methods in Android applications.

Uploaded by

hareeshmajnu1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Mobile Application Development Unit-II

Unit 2: Basic Widgets:


Syllabus: Understanding the Role of Android Application Components, Understanding the Utility
of Android API, Overview of the Android Project Files, Understanding Activities, Role of the
Android Manifest File, Creating the User Interface, Commonly Used Layouts and Controls, Event
Handling, Displaying Messages Through Toast, Creating and Starting an Activity, Using the Edit
Text Control, Choosing Options with Checkbox, Choosing Mutually Exclusive Items Using Radio
Buttons.

UNDERSTANDING THE ROLE OF ANDROID APPLICATION COMPONENTS


An android component is simply a piece of code
that has a well defined life cycle e.g. Activity,
Receiver, Service etc.
The core building blocks or fundamental
components of android are activities, views,
intents, services, content providers, fragments and
AndroidManifest.xml.
Activity:
An activity is a class that represents a single screen.
It is like a Frame in AWT.
View:
A view is the UI element such as button, label, text field etc. Anything that you see is a view.
Intent:
Intent is used to invoke components. It is mainly used to:
 Start the service
 Launch an activity
 Display a web page
 Display a list of contacts
 Broadcast a message
 Dial a phone call etc.
For example, you may write the following code to view the webpage.
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent);

Page 1
Mobile Application Development Unit-II

Service:
Service is a background process that can run for a long time.
There are two types of services local and remote. Local service is accessed from within the
application whereas remote service is accessed remotely from other applications running on the
same device.
Content Provider:
Content Providers are used to share data between the applications.
Fragment:
Fragments are like parts of activity. An activity can display one or more fragments on the screen at
the same time.

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;
permissions that applications might require; intents; and much more. The framework API is
specified through an integer called API level, and each Android platform version supports exactly
one API level. The initial release of the Android platform provided API Level 1, and subsequent
releases have incremented the API level.

Code Version Initial release API


name number date level

No Codename 1.0 September 23, 2008 1

Petit Four 1.1 February 9, 2009 2

Cupcake 1.5 April 27, 2009 3

Donut 1.6 September 15, 2009 4

Eclair 2.0 – 2.1 October 26, 2009 5–7

Froyo 2.2 – 2.2.3 May 20, 2010 8

Gingerbread 2.3 – 2.3.7 December 6, 2010 9 – 10

Honeycomb 3.0 – 3.2.6 February 22, 2011 11 – 13

Page 2
Mobile Application Development Unit-II

Ice Cream Sandwich 4.0 – 4.0.4 October 18, 2011 14 – 15

Jelly Bean 4.1 – 4.3.1 July 9, 2012 16 – 18

KitKat 4.4 – 4.4.4 October 31, 2013 19 – 20

Lollipop 5.0 – 5.1.1 November 12, 2014 21 – 22

Marshmallow 6.0 – 6.0.1 October 5, 2015 23

Nougat 7.0 – 7.1.2 August 22, 2016 24 – 25

Oreo 8.0 – 8.1 August 21, 2017 26 – 27

Pie 9.0 August 6, 2018 28

Q 10.0 29

OVERVIEW OF THE ANDROID PROJECT FILES

Android application contains different components such as java source code, string resources,
images, manifest file, apk file etc. Let's understand the project structure of android application.

Page 3
Mobile Application Development Unit-II

UNDERSTANDING ACTIVITIES
An activity is the single screen in android. It is like window or frame of Java.
Every unique screen the user interacts with in an application is displayed through an Activity—one
Activity for each screen. Users can interact with an application by performing different actions with
the visual controls found in the Activity. A simple application may consist of just one Activity,
whereas large applications contain several Activities. Each Activity of an application operates
independently of the others. A stack of Activities is maintained while running an application and
the Activity at the top of the stack is the one currently being displayed.
Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android
Activity is the subclass of ContextThemeWrapper class.
By the help of activity, you can place all your UI components or widgets in a single screen.
The 7 lifecycle method of Activity describes how activity will behave at different states.
Android Activity Lifecycle methods
Let's see the 7 lifecycle methods of android activity.

Method Description

onCreate() called when activity is first created.

onStart() called when activity is becoming visible to the user.

onResume() called when activity will start interacting with the user.

onPause() called when activity is not visible to the user.

onStop() called when activity is no longer visible to the user.

onRestart() called after your activity is stopped, prior to start.

onDestroy() called before the activity is destroyed.

Page 4
Mobile Application Development Unit-II

File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/
apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.activitylifecycle.MainActivity">

Page 5
Mobile Application Development Unit-II

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="#00ffff"
android:textColor="#ff0000"
android:textStyle="bold"
android:typeface="monospace"
android:textSize="35dp"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

It provides the details about the invocation of life cycle methods of activity. In this example, we are
displaying the content on the logcat.

File: MainActivity.java
package example.javatpoint.com.activitylifecycle;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart()
{

Page 6
Mobile Application Development Unit-II

super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume()
{
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause()
{
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop()
{
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart()
{
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy()
{
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}

Page 7
Mobile Application Development Unit-II

Output:

You will not see any output on the emulator or device. You need to open logcat.

Now see on the logcat: onCreate, onStart and onResume methods are invoked.

Now click on the HOME Button. You will see onPause method is invoked.

Page 8
Mobile Application Development Unit-II

After a while, you will see onStop method is invoked.

Now see on the emulator. It is on the home. Now click on the center button to launch the app again.

Now click on the ActivityLifeCycle App icon.

Page 9
Mobile Application Development Unit-II

Now see on the logcat: onRestart, onStart and onResume methods are invoked.

If you see the emulator, application is started again.

Now click on the back button. Now you will see onPause methods is invoked.

Page
10
Mobile Application Development Unit-II

After a while, you will see onStop and onDestroy methods are invoked.

Note:The onCreate() and onDestroy() methods are called only once throughout the activity
lifecycle.

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. It’s an XML file that defines the overall structure
and information about the application
AndroidManifest.xml file in android
The AndroidManifest.xml file contains information of your package, including components of the
application such as activities, services, broadcast receivers, content providers etc.
It performs some other tasks also:
 It is responsible to protect the application to access any protected parts by
providing the permissions.
 It also declares the android API that the application is going to use.
 It lists the instrumentation classes. The instrumentation classes provide profiling
and other information’s. Thisinformation’s are removed just before the application is
published etc.

This is the required xml file for all the android application and located inside the root directory.

A simple AndroidManifest.xml file looks like this:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javatpoint.hello"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk

Page
11
Mobile Application Development Unit-II

android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<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:
 android—Identifies the Android namespace used to provide several system attributes used
within the application.
 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.
 versionCode/versionName—The versionCode attribute is used to define the current
application version. The version is used internally to compare application versions.
The versionName attribute is used to specify a version number that is displayed to users.
 <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 value is “1.” For example, the following attribute says that
the minimum API level required by the application is 15:
android:minSdkVersion="15"
Hence, the application will run on API Level 15 and above, but will not run on API Level 14 or
below.

Page
12
Mobile Application Development Unit-II

 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; that is, the application cannot run on an API level higher than the one specified
in this attribute. While installing the application, the Android system checks the <uses-
sdk> attributes defined in the application’s manifest files and compares it with its own
internal API level. The application can be installed only if
The value of the android:minSdkVersion attribute of the application must be less than or equal
to the system’s API level. If the android:minSdkVersion attribute is not declared, it is assumed
that the application requires API Level 1.
The value of the android:maxSdkVersion attribute of the application (if it is declared) must be
equal to, or greater than, the system’s API level.
 <application> tag—Nested within <manifest> is <application>, which is the parent of
application control tags. The icon and label attributes of the application tag refer to icon and
label resources that will be displayed in Android devices to represent the application
 <activity> tag—Nested within <application> is the <activity> tag, which describes an
Activity component. This tag’s name attribute identifies a class that is an
Activity, WelcomeMsgActivity
 <intent- filter>—Nested within <activity> is the <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 this Activity available from the
application launcher, allowing it to launch when the application starts. Basically,
the <intent-filter> tag declares the capabilities of different components through the
nested <action> and <category> tags.
Besides the preceding default tags used in the manifest file, the following are some of the most
commonly used tags:
 <service> tags—Used for declaring services. Services refer to the processes that run in the
background without a user interface. They perform required processing and handle events
silently without user interaction.
 <receiver> tags—Used for declaring broadcast receivers. Broadcast receivers are used to
listen and respond to broadcast announcements. Applications initiate broadcasts for the
interested applications when some event occurs that requires attention; for example,
essential information or confirmation is required from the user before taking some
destructive action. An application can have any number of broadcast receivers. A broadcast
receiver responds by taking a specific action.

Page
13
Mobile Application Development Unit-II

 <provider> tags—Used for declaring content providers. Content providers provide content,
that is, data to applications. They help in handling, storing, and sharing data such as audio,
images, video, and contact lists with other applications. Android ships with a number of
content providers that the applications can use to access and share data with other
applications.
 <uses-permission> tags—Used for declaring the permissions 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
Note
The <uses-permission> tags are nested within <manifest> tags. They appear at the same level
as the <application> tag.

CREATING THE USER INTERFACE


There are three approaches to creating user interfaces in Android.
1. You can create user interfaces entirely in Java code or
2. Entirely in XML or in both (defining the user interface in XML and then referring and
modifying it through Java code).
3. The third approach, the combined approach, is highly preferred
The XML file in which you create the user interface is activity_main.xml found in
the res/layout folder. In the activity_main.xml file, different controls or views that you want to
interact with the user are defined. The controls or views in activity_main.xml have to be laid out in
some way. The default layout in which the controls or views are usually arranged
is RelativeLayout. The activity_main.xml file is also referred to as the Activity layout file.
Default Code in the activity_main.xml File
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.co
m/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.activitylifecycle.MainActivity">
Page
14
Mobile Application Development Unit-II

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="#00ffff"
android:textColor="#ff0000"
android:textStyle="bold"
android:typeface="monospace"
android:textSize="35dp"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

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. The layouts also known as Containers or
ViewGroups are used for organizing the views or controls in the required format. Examples of
layouts are LinearLayout, FrameLayout, and so on.
A brief description of layouts follows:
 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. Depending on the orientation parameter, elements are either
arranged in row or column format.
 RelativeLayout—In this layout, each child element is laid out in relation to other child
elements. That is, a child element appears in relation to the previous child. Also, the
elements are laid out in relation to the parent.
 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
and hence is deprecated.
 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

Page
15
Mobile Application Development Unit-II

the FrameLayout overlaps the previous view; that is, each view stacks on top of the previous
one.
 TableLayout—In this layout, the screen is assumed to be divided in table rows, and each of
the child elements is arranged in a specific row and column.
 GridLayout—In this layout, child views are arranged in a grid format, that is, 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.
A brief description of Controls follows:
The following list highlights some of the controls commonly used in Android applications:
 TextView—A read-only text label. It supports multiline display, string formatting, and
automatic word wrapping.
 EditText—An editable text box that also accepts multiline entry and word-wrapping.
 ListView—A ViewGroup that creates and manages a vertical list of views, displaying them
as rows within the list.
 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.
 Button—A standard command button.
 CheckBox—A button allowing a user to select (check) or unselect (uncheck).
 RadioButton—A mutually exclusive button, which, when selected, unselects all other
buttons in the group.

1 TextView
This control is used to display text to the user.

2 EditText
EditText is a predefined subclass of TextView that includes rich editing capabilities.

3 AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except that it
shows a list of completion suggestions automatically while the user is typing.

4 Button
A push-button that can be pressed, or clicked, by the user to perform an action.

5 ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the exact
location of its children. This shows a button with an image (instead of text) that can

Page
16
Mobile Application Development Unit-II

be pressed or clicked by the user.

6 CheckBox
An on/off switch that can be toggled by the user. You should use check box when
presenting users with a group of selectable options that are not mutually exclusive.

7 ToggleButton
An on/off button with a light indicator.

8 RadioButton
The RadioButton has two states: either checked or unchecked.

9 RadioGroup
A RadioGroup is used to group together one or more RadioButtons.

10 ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks, such as
when you are performing a task in the background.

11 Spinner
A drop-down list that allows users to select one value from a set.

12 TimePicker
The TimePicker view enables users to select a time of the day, in either 24-hour
mode or AM/PM mode.

13 DatePicker
The DatePicker view enables users to select a date of the day.

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 reaction to the event, that is, 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. When an event occurs,
the listeners detect it and direct the program to the appropriate routine.

Page
17
Mobile Application Development Unit-II

An event listener is an interface in the View class that contains a single callback method,
called an event occurrence.
For example the callback method onClick() is called when the user clicks on a button. For event
handling, the event listener is either implemented in the Activity class or is defined as
an anonymous class. Thereafter, an instance of the implementation is passed to the respective
control through the setOnClickListener() method.
Note:Click is just one type of an event.
Drag the component or write the code for UI in activity_main.xml
First of all, drag 2 textfields from the Text Fields palette and one button from the Form Widgets
palette as shown in the following figure.

The generated code for the ui components will be like this:

File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.eventhandling.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

Page
18
Mobile Application Development Unit-II

android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#00ffff"
android:gravity="center"
android:text="Enter First Num"
android:textColor="#ff0000"
android:textSize="15dp"
android:textStyle="bold"
android:typeface="monospace"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="63dp"
android:layout_toEndOf="@+id/textView"
android:layout_toRightOf="@+id/textView"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
tools:layout_editor_absoluteY="53dp" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"

Page
19
Mobile Application Development Unit-II

android:background="#00ffff"
android:gravity="center"
android:text="Enter Second Num"
android:textColor="#ff0000"
android:textSize="15dp"
android:textStyle="bold"
android:typeface="monospace"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignStart="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="28dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
tools:layout_editor_absoluteY="127dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="109dp"
android:text="ADD"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="266dp" />
</RelativeLayout>

Page
20
Mobile Application Development Unit-II

Activity class
Now write the code to display the sum of two numbers.
File: MainActivity.java
package in.kvsw.eventhandling;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivityextends AppCompatActivity
{
private EditTextedittext1, edittext2;
private Button buttonSum;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton()
{
edittext1 = (EditText) findViewById(R.id.editText1);
edittext2 = (EditText) findViewById(R.id.editText2);
buttonSum= (Button) findViewById(R.id.button);
buttonSum.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
String value1=edittext1.getText().toString();
String value2=edittext2.getText().toString();
int a=Integer.parseInt(value1);
int b=Integer.parseInt(value2);

Page
21
Mobile Application Development Unit-II

int sum=a+b;
Toast.makeText(getApplicationContext(),String.valueOf(sum),
Toast.LENGTH_LONG).show();
}
});
}
}

Output:

DISPLAYING MESSAGES THROUGH TOAST


A Toast is a transient message that automatically disappears after a while without user interaction.
It is usually used to inform the user about happenings that are not very important and does not
create a problem if they go unnoticed.
A Toast is created by calling the static method, makeText(), of the Toast class. The syntax of
the makeText() method is shown here:
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.
The method returns a Toast instance. You call the show() method on the returned Toastinstance to
display the containing string or message.
Page
22
Mobile Application Development Unit-II

Example: Same Example of Event Handling

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.
For example, The default behavior of the EditText control is to
display text as a single line and run over to the next line when the
user types beyond the width of the control. By applying attributes,
you can constrain the 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.
Attributes Used to Configure the EditText Control

The following is a list of attributes that can be used to configure


the EditText control:
 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

Page
23
Mobile Application Development Unit-II

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.
 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.
 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. 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.
 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" displays the text Enter your name in
the EditText control to indicate that a name has to be entered in this EditText control.
 android:lines—Sets the height of the EditText control to accommodate the specified
number of lines.
For example, android:lines="5" sets the height of EditText control to accommodate five
lines. Typing text beyond the fifth line causes the text to scroll up to accommodate input.
 android:textSize—Sets the size of the text typed in the EditText control. Y
ou can specify the size in any of the following units of measurement: px, in, mm, pts, dip,
and sp.
For example, android:textSize="15px" sets the size of text typed in the EditText control to
15 pixels.
The recommended unit for text size is sp as it works correctly across different screen sizes
and densities.
 android:autoText—When set to true enables the EditText control to correct common
spelling mistakes.
 android:capitalize—Automatically converts typed text into capital letters.
The valid values are none, characters, words, and sentences.

Page
24
Mobile Application Development Unit-II

 android:password—When set to true, the attribute converts the typed characters into dots
to hide entered text.
 android:minWidth—Used to specify the minimum width of the control.
 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.
 android:minHeight—Used to specify the minimum height of the control.
 android:maxHeight—Used to specify the maximum height of the control.
 android:scrollHorizontally—When set to true, makes the text scroll horizontally if typed
beyond the specified width of the control.
 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, textCapCharacters, textCapWords, textEmailAddress, datetime
, date, time, textAutoCorrect, textMultiLine, and textPassword.
The following keypads show how the onscreen keyboard changes when the
values number, phone, text, textCap Characters, and textEmailAddress are assigned to this
attribute, respectively.
This single attribute actually replaces many attributes such as
android:number, android:phoneNumber, android:text, android:capitalize,
and android: textEmailAddress.

Page
25
Mobile Application Development Unit-II

Drag the component or write the code for UI in activity_main.xml


First of all, drag 2 TextView Controls, 2 textfields from the Text Fields paletteand one button from
the Form Widgets palette as shown in the following figure.

The generated code for the UIcomponents will be like this:

Example: Same Example of Event Handling

CHOOSING OPTIONS WITH CHECKBOX


A checkbox control has two states:
 checked and
 unchecked.
When the check box is selected, it toggles its state from checked to unchecked and vice versa.
A check box is created via an instance of android.widget.CheckBox.
In Java, the following methods can be used with Checkbox controls:
 isChecked()—Determines whether the check box is checked
 setChecked()—Sets or changes the state of the check box
 toggle()—Toggles the state of the check box from checked to unchecked or vice versa
To add an event listener, you can implement the OnCheckedChangeListener interface that invokes
the callback method onCheckedChanged() when the state of the check box changes.

Page
26
Mobile Application Development Unit-II

Methods of CheckBox class

There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
Some of them are as follows:

Method Description

public booleanisChecked() Returns true if it is checked otherwise false.

public void setChecked(boolean status) Changes the state of the CheckBox.

activity_main.xml

Drag one TextView, three checkboxes and one button for the layout. Now the activity_main.xml
file will look like this:

File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android
.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.checkbox.MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="370dp"
android:layout_height="42dp"
android:background="#00ffff"
android:gravity="center"
android:text="Select the Items you want"
android:textColor="#ff0000"
android:textSize="25dp"
android:textStyle="bold"
tools:layout_editor_absoluteX="17dp"
tools:layout_editor_absoluteY="18dp" />

Page
27
Mobile Application Development Unit-II

<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="68dp"
android:text="Pizza"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Coffee"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox" />

<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Burger"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox2" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"

Page
28
Mobile Application Development Unit-II

android:layout_marginTop="184dp"
android:text="Order"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox3" />

</android.support.constraint.ConstraintLayout>

Activity class
Let's write the code to check which toggle button is ON/OFF.
File: MainActivity.java
package in.kvsw.checkbox;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivityextends AppCompatActivity
{
CheckBoxpizza,coffe,burger;
Button buttonOrder;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick()
{ //Getting instance of CheckBoxes and Button from the activty_main.xml file
pizza=(CheckBox)findViewById(R.id.checkBox);
coffe=(CheckBox)findViewById(R.id.checkBox2);
burger=(CheckBox)findViewById(R.id.checkBox3);
buttonOrder=(Button)findViewById(R.id.button);
//Applying the Listener on the Button click
Page
29
Mobile Application Development Unit-II

buttonOrder.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
int totalamount=0;
StringBuilder result=new StringBuilder();
result.append("Selected Items:");
if(pizza.isChecked())
{
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked())
{
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked())
{
result.append("\nBurger 120Rs");
totalamount+=120;
}
result.append("\nTotal: "+totalamount+"Rs");
//Displaying the message on the toast
Toast.makeText(getApplicationContext(), result.toString(),
Toast.LENGTH_LONG).show();
}
});
}
}

Page
30
Mobile Application Development Unit-II

Output:

CHOOSING MUTUALLY EXCLUSIVE ITEMS USING RADIOBUTTONS

RadioButton is a two states button which is either checked or unchecked. If a single radio
button is unchecked, we can click it to make checked radio button. Once a radio button is checked,
it cannot be marked as unchecked by user.
The difference between check boxes and radio buttons is that you can select more than one
check box in a set, whereas radio buttons are mutually exclusive—only one radio button can be
selected in a group.
Selecting a radio button automatically deselects other radio buttons in the group.
To make them mutually exclusive, RadioButton controls are grouped together into
the RadioGroupelement 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 RadioButton controls.
In Java, the following methods can be applied to RadioButtons:
 isChecked()—Detects whether the RadioButton control is selected.
 toggle()—Toggles the state of the RadioButton from selected to unselected and vice versa.
 check()—Checks a specific RadioButton whose ID is supplied in the method.
 getCheckedRadioButtonId()—Gets the ID of the currently selected RadioButton control.
It returns –1 if no RadioButton control is checked.

Page
31
Mobile Application Development Unit-II

We are going to implement radio button in RadioGroup.


File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="in.kvsw.radiobuttons.MainActivity">

<View

android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="20dp"
android:background="#B8B894" />
<TextView

android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:background="#00ffff"
android:textColor="#ff0000"
android:textStyle="bold"
android:textSize="22dp"
android:text="Select Gender of the Student" />
<!-- Customized RadioButtons -->
<RadioGroup

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioGroup">

Page
32
Mobile Application Development Unit-II

<RadioButton

android:id="@+id/radioMale"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Male"
android:layout_marginTop="10dp"
android:checked="false"
android:textSize="20dp" />

<RadioButton

android:id="@+id/radioFemale"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Female"
android:layout_marginTop="20dp"
android:checked="false"
android:textSize="20dp" />

</RadioGroup>
<Button

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected"
android:id="@+id/button"
android:onClick="onclickbuttonMethod"
android:layout_gravity="center_horizontal" />

</LinearLayout>

Activity class
File: MainActivity.java
package in.kvsw.radiobuttons;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

Page
33
Mobile Application Development Unit-II

import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivityextends AppCompatActivity
{
Button button;
RadioButtongenderradioButton;
RadioGroupradioGroup;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuttonMethod(View v)
{
int selectedId = radioGroup.getCheckedRadioButtonId();
genderradioButton= (RadioButton) findViewById(selectedId);
if(selectedId==-1)
{
Toast.makeText(MainActivity.this,"Nothing selected",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,genderradioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
}

Page
34
Mobile Application Development Unit-II

Output

Page
35

You might also like