Unit-1: Project Structure of Mobile Application

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

405-Mobile Application Development-2

Unit-1: Project structure of Mobile Application


1.1 Internal details of Android Application
 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.

1. Java Source Code


Let's see the java source file created by the Eclipse IDE:
File: MainActivity.java
package com.example.helloandroid;

Shri S.V.Patel College of C.S. and B.M. Page 1


405-Mobile Application Development-2

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {//(1)
@Override
protected void onCreate(Bundle savedInstanceState) {//(2)
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);//(3)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {//(4)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
(1) Activity is a java class that creates and default window on the screen where we
can place different components such as Button, EditText, TextView, Spinner etc. It
is like the Frame of Java AWT.
It provides life cycle methods for activity such as onCreate, onStop, OnResume
etc.
(2) The onCreate method is called when Activity class is first created.
(3) The setContentView(R.layout.activity_main) gives information about our
layout resource. Here, our layout resources are defined in activity_main.xml file.
2. activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

Shri S.V.Patel College of C.S. and B.M. Page 2


405-Mobile Application Development-2

android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
 As you can see, a textview is created by the framework automatically. But
the message for this string is defined in the strings.xml file.
The @string/hello_world provides information about the textview message.
The value of the attribute hello_world is defined in the strings.xml file.

3. strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">helloandroid</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
</resources>
You can change the value of the hello_world attribute from this file.

4. Generated R.java file


It is the auto-generated file that contains IDs for all the resources of res directory.
It is generated by aapt(Android Asset Packaging Tool). Whenever you create any
component on activity_main, a corresponding ID is created in the R.java file which
can be used in the Java Source file later.
File: R.java
5. APK File

Shri S.V.Patel College of C.S. and B.M. Page 3


405-Mobile Application Development-2

An apk file is created by the framework automatically. If you want to run the
android application on the mobile, transfer and install it.

6. Resources
It contains resource files including activity_main, strings, styles etc.

7. Manifest file
It contains information about package including components such as activities,
services, content providers etc.

1.1.1 Dalvik VM, Screen Orientation


1. Dalvik Virtual Machine

 Dalvik Virtual Machine is a Register-Based virtual machine. It was designed


and written by Dan Bornstein with contributions of other Google engineers
as part of the Android mobile phone platform.
 Working of DVM
The Java Compiler (javac) converts the Java Source Code into Java Byte-Code
(.class). Then DEX Compiler converts this (.class) file into in Dalvik Byte Code
i.e. “.dex” file.

Shri S.V.Patel College of C.S. and B.M. Page 4


405-Mobile Application Development-2

Application
 For Android, a new Virtual machine was developed by Google as stated
above. It uses registers of the CPU to store the operands. So no requirement
of any pushing and popping of instructions. Hence making execution faster.
The instructions operate on virtual registers, being those virtual registers
memory positions in the host device. Register-based models are good at
optimizing and running on low memory. They can store common sub-
expression results which can be used again in the future. This is not possible
in a Stack-based model at all. Dalvik Virtual Machine uses its own byte-
code and runs “.dex”(Dalvik Executable File) file.

Shri S.V.Patel College of C.S. and B.M. Page 5


405-Mobile Application Development-2

Advantages
 DVM supports the Android operating system only.
 In DVM executable is APK.
 Execution is faster.
 From Android 2.2 SDK Dalvik has it’s own JIT (Just In Time) compiler.
 DVM has been designed so that a device can run multiple instances of the
Virtual Machine effectively.
 Applications are given their own instances.
Disadvantages
 DVM supports only Android Operating System.
 For DVM very few Re-Tools are available.
 Requires more instructions than register machines to implement the same high-
level code.
 App Installation takes more time due to dex.
 More internal storage is required.

Difference Between DVM and JVM

Shri S.V.Patel College of C.S. and B.M. Page 6


405-Mobile Application Development-2

Serial DVM
JVM (Java Virtual Machine)
No.
1 It is Register based which is designed to run on low memory. It is Stack based.
DVM uses its own byte code and runs the “.Dex” file. From JVM uses java byte code and runs
2
Android 2.2 SDK Dalvik has got a Just in Time compiler “.class” file having JIT (Just In Time).
DVM has been designed so that a device can run multiple
A single instance of JVM is shared with
3 instances of the VM efficiently. Applications are given their own
multiple applications.
instance.
JVM supports multiple operating
4 DVM supports the Android operating system only.
systems.
5 For DVM very few Re-tools are available For JVM many Re-tools are available.
6 There is a constant pool for every application. It has a constant pool for every class.
7 Here the executable is APK. Here the executable is JAR.

2. Screen Orientation
 The screenOrientation is the attribute of activity element. The orientation of
android activity can be portrait, landscape, sensor, unspecified etc. You need to
define it in the AndroidManifest.xml file.
 Syntax:
<activity android:name="package_name.Your_ActivityName"
android:screenOrientation="orirntation_type">
</activity>

Example:

<activity android:name=" example.javatpoint.com.screenorientation.MainActivity"


android:screenOrientation="portrait">
</activity>
<activity android:name=".SecondActivity"
android:screenOrientation="landscape">
</activity>

Shri S.V.Patel College of C.S. and B.M. Page 7


405-Mobile Application Development-2

The common values for screenOrientation attribute are as follows:

Value Description

Unspecified It is the default value. In such case, system chooses the orientation.

Portrait taller not wider

Landscape wider not taller

Sensor orientation is determined by the device orientation sensor.

Android Portrait and Landscape mode screen orientation example

In this example, we will create two activities of different screen orientation. The
first activity (MainActivity) will be as "portrait" orientation and second activity
(SecondActivity) as "landscape" orientation type.

activity_main.xml

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.screenorientation.MainActivity">

<Button

Shri S.V.Patel College of C.S. and B.M. Page 8


405-Mobile Application Development-2

android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="112dp"
android:onClick="onClick"
android:text="Launch next activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.612"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText1"
app:layout_constraintVertical_bias="0.613" />

<TextView
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="124dp"
android:ems="10"
android:textSize="22dp"
android:text="This activity is portrait orientation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Activity class

File: MainActivity.java

Shri S.V.Patel College of C.S. and B.M. Page 9


405-Mobile Application Development-2

package example.javatpoint.com.screenorientation;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button1=(Button)findViewById(R.id.button1);
}
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
}

activity_second.xml

File: activity_second.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"

Shri S.V.Patel College of C.S. and B.M. Page 10


405-Mobile Application Development-2

tools:context="example.javatpoint.com.screenorientation.SecondActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="180dp"
android:text="this is landscape orientation"
android:textSize="22dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

SecondActivity class

File: SecondActivity.java

package example.javatpoint.com.screenorientation;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SecondActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

}
}

Shri S.V.Patel College of C.S. and B.M. Page 11


405-Mobile Application Development-2

AndroidManifest.xml

File: AndroidManifest.xml

In AndroidManifest.xml file add the screenOrientation attribute in activity and


provides its orientation. In this example, we provide "portrait" orientation for
MainActivity and "landscape" for SecondActivity.

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.javatpoint.com.screenorientation">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="example.javatpoint.com.screenorientation.MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<activity android:name=".SecondActivity"
android:screenOrientation="landscape">
</activity>
</application>

</manifest>

Shri S.V.Patel College of C.S. and B.M. Page 12


405-Mobile Application Development-2

Output:

Shri S.V.Patel College of C.S. and B.M. Page 13


405-Mobile Application Development-2

1.1.2 AndroidMenifest, R.java

1. AndroidMenifest
Every app project must have an AndroidManifest.xml file (with precisely that
name) at the root of the project source set. The manifest file describes essential
information about your app to the Android build tools, the Android operating
system, and Google Play.
Among many other things, the manifest file is required to declare the following:

 The app's package name, which usually matches your code's namespace. The
Android build tools use this to determine the location of code entities when
building your project. When packaging the app, the build tools replace this value
with the application ID from the Gradle build files, which is used as the unique app
identifier on the system and on Google Play. Read more about the package name
and app ID.
 The components of the app, which include all activities, services, broadcast
receivers, and content providers. Each component must define basic properties
such as the name of its Kotlin or Java class. It can also declare capabilities such as
which device configurations it can handle, and intent filters that describe how the
component can be started. Read more about app components.
 The permissions that the app needs in order to access protected parts of the system
or other apps. It also declares any permissions that other apps must have if they
want to access content from this app. Read more about permissions.
 The hardware and software features the app requires, which affects which devices
can install the app from Google Play. Read more about device compatibility.

If you're using Android Studio to build your app, the manifest file is created for
you, and most of the essential manifest elements are added as you build your app
(especially when using code templates).

Shri S.V.Patel College of C.S. and B.M. Page 14


405-Mobile Application Development-2

File features

The following sections describe how some of the most important characteristics of
your app are reflected in the manifest file.

Package name and application ID

The manifest file's root element requires an attribute for your app's package name
(usually matching your project directory structure—the Java namespace).
For example, the following snippet shows the root <manifest> element with the
package name "com.example.myapp":

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp"
android:versionCode="1"
android:versionName="1.0" >
...
</manifest>

While building your app into the final application package (APK), the Android
build tools use the package attribute for two things:

 It applies this name as the namespace for your app's generated R.java class (used to
access your app resources).
Example: With the above manifest, the R class is created
at com.example.myapp.R.
 It uses this name to resolve any relative class names that are declared in the
manifest file.
Example: With the above manifest, an activity declared as <activity
android:name=".MainActivity"> is resolved to
be com.example.myapp.MainActivity.

As such, the name in the manifest's package attribute should always match your
project's base package name where you keep your activities and other app code. Of
course, you can have other sub-packages in your project, but those files must
import the R.java class using the namespace from the package attribute.

Shri S.V.Patel College of C.S. and B.M. Page 15


405-Mobile Application Development-2

However, beware that, once the APK is compiled, the package attribute also
represents your app's universally unique application ID. After the build tools
perform the above tasks based on the package name, they replace
the package value with the value given to the applicationId property in your
project's build.gradle file (used in Android Studio projects). This final value for
the package attribute must be universally unique because it is the only guaranteed
way to identify your app on the system and in Google Play.

The distinction between the package name in the manifest and the applicationId in
the build.gradle file can be a bit confusing. But if you keep them same, you have
nothing to worry about.

However, if you decide to make your code's namespace (and thus,


the package name in the manifest) something different from the applicationId from
the build file, be sure you fully understand the implications of setting the
application ID. That page explains how you can safely adjust the
manifest's package name independent of the build file's applicationId, and change
the application ID for different build configurations.

App components

For each app component that you create in your app, you must declare a
corresponding XML element in the manifest file:
 <activity> for each subclass of Activity.
 <service> for each subclass of Service.
 <receiver> for each subclass of BroadcastReceiver.
 <provider> for each subclass of ContentProvider.

If you subclass any of these components without declaring it in the manifest file,
the system cannot start it.

The name of your subclass must be specified with the name attribute, using the full
package designation. For example, an Activity subclass can be declared as follows:
<manifest ... >
<application ... >
<activity android:name="com.example.myapp.MainActivity" ... >
</activity>

Shri S.V.Patel College of C.S. and B.M. Page 16


405-Mobile Application Development-2

</application>
</manifest>

However, if the first character in the name value is a period, the app's package
name (from the <manifest> element's package attribute) is prefixed to the name.
For example, the following activity name is resolved to
`"com.example.myapp.MainActivity"`:
<manifest package="com.example.myapp" ... >
<application ... >
<activity android:name=".MainActivity" ... >
...
</activity>
</application>
</manifest>

If you have app components that reside in sub-packages (such as


in com.example.myapp.purchases), the name value must add the missing sub-
package names (such as ".purchases.PayActivity") or use the fully-qualified
package name.

Intent filters
App activities, services, and broadcast receivers are activated by intents. An intent
is a message defined by an Intent object that describes an action to perform,
including the data to be acted upon, the category of component that should perform
the action, and other instructions.
When an app issues an intent to the system, the system locates an app component
that can handle the intent based on intent filter declarations in each app's manifest
file. The system launches an instance of the matching component and passes
the Intent object to that component. If more than one app can handle the intent,
then the user can select which app to use.

An app component can have any number of intent filters (defined with the <intent-
filter> element), each one describing a different capability of that component.

For more information, see the Intents and Intent Filters document.

Icons and labels

Shri S.V.Patel College of C.S. and B.M. Page 17


405-Mobile Application Development-2

A number of manifest elements have icon and label attributes for displaying a
small icon and a text label, respectively, to users for the corresponding app
component.

In every case, the icon and label that are set in a parent element become the
default icon and label value for all child elements. For example, the icon and label
that are set in the <application> element are the default icon and label for each of
the app's components (such as all activities).

The icon and label that are set in a component's <intent-filter> are shown to the
user whenever that component is presented as an option to fulfill an intent. By
default, this icon is inherited from whichever icon is declared for the parent
component (either the <activity> or <application> element), but you might want to
change the icon for an intent filter if it provides a unique action that you'd like to
better indicate in the chooser dialog. For more information, see Allow Other Apps
to Start Your Activity.

Permissions

Android apps must request permission to access sensitive user data (such as
contacts and SMS) or certain system features (such as the camera and internet
access). Each permission is identified by a unique label. For example, an app that
needs to send SMS messages must have the following line in the manifest:
<manifest ... >
<uses-permission android:name="android.permission.SEND_SMS"/>
...
</manifest>

Beginning with Android 6.0 (API level 23), the user can approve or reject some
app permisions at runtime. But no matter which Android version your app
supports, you must declare all permission requests with a <uses-
permission> element in the manifest. If the permission is granted, the app is able to
use the protected features. If not, its attempts to access those features fail.
Your app can also protect its own components with permissions. It can use any of
the permissions that are defined by Android, as listed
in android.Manifest.permission, or a permission that's declared in another app.
Your app can also define its own permissions. A new permission is declared with
the <permission> element.

Shri S.V.Patel College of C.S. and B.M. Page 18


405-Mobile Application Development-2

For more information, see the Permissions Overview.

Device compatibility

The manifest file is also where you can declare what types of hardware or software
features your app requires, and thus, which types of devices your app is compatible
with. Google Play Store does not allow your app to be installed on devices that
don't provide the features or system version that your app requires.
There are several manifest tags that define which devices your app is compatible
with. The following are just a couple of the most common tags.

<uses-feature>
The <uses-feature> element allows you to declare hardware and software features
your app needs. For example, if your app cannot achieve basic functionality on a
device without a compass sensor, you can declare the compass sensor as required
with the following manifest tag:
<manifest ... >
<uses-feature android:name="android.hardware.sensor.compass"
android:required="true" />
...
</manifest>

Note: If you'd like to make your app available on Chromebooks, there are some
important hardware and software feature limitations that you should consider. For
more information, see App Manifest Compatibility for Chromebooks.

<uses-sdk>
Each successive platform version often adds new APIs not available in the
previous version. To indicate the minimum version with which your app is
compatible, your manifest must include the <uses-sdk> tag and
its minSdkVersion attribute.

However, beware that attributes in the <uses-sdk> element are overridden by


corresponding properties in the build.gradle file. So if you're using Android Studio,
you must specify the minSdkVersion and targetSdkVersion values there instead:

Shri S.V.Patel College of C.S. and B.M. Page 19


405-Mobile Application Development-2

GroovyKotlin

android {
defaultConfig {
applicationId 'com.example.myapp'

// Defines the minimum API level required to run the app.


minSdkVersion 15

// Specifies the API level used to test the app.


targetSdkVersion 28

...
}
}

For more information about the build.gradle file, read about how to configure your
build.

To learn more about how to declare your app's support for different devices, see
the Device Compatibility Overview.

File conventions

This section describes the conventions and rules that generally apply to all
elements and attributes in the manifest file.

Elements
Only the <manifest> and <application> elements are required. They each
must occur only once. Most of the other elements can occur zero or more
times. However, some of them must be present to make the manifest file
useful.

All of the values are set through attributes, not as character data within an
element.

Elements at the same level are generally not ordered. For example,
the <activity>, <provider>, and <service> elements can be placed in any
order. There are two key exceptions to this rule:

Shri S.V.Patel College of C.S. and B.M. Page 20


405-Mobile Application Development-2

 An <activity-alias> element must follow the <activity> for which it is an


alias.
 The <application> element must be the last element inside
the <manifest> element.

Attributes
Technically, all attributes are optional. However, many attributes must be
specified so that an element can accomplish its purpose. For truly optional
attributes, the reference documentation indicates the default values.

Except for some attributes of the root <manifest> element, all attribute
names begin with an android: prefix. For
example, android:alwaysRetainTaskState. Because the prefix is universal,
the documentation generally omits it when referring to attributes by name.

Multiple values
If more than one value can be specified, the element is almost always
repeated, rather than multiple values being listed within a single element.
For example, an intent filter can list several actions:

<intent-filter ... >


<action android:name="android.intent.action.EDIT" />
<action android:name="android.intent.action.INSERT" />
<action android:name="android.intent.action.DELETE" />
...
</intent-filter>

Resource values
Some attributes have values that are displayed to users, such as the title for
an activity or your app icon. The value for these attributes might differ based
on the user's language or other device configurations (such as to provide a
different icon size based on the device's pixel density), so the values should
be set from a resource or theme, instead of hard-coded into the manifest file.
The actual value can then change based on alternative resources that you
provide for different device configurations.
Resources are expressed as values with the following format:

Shri S.V.Patel College of C.S. and B.M. Page 21


405-Mobile Application Development-2

"@[package:]type/name"

You can omit the package name if the resource is provided by your app
(including if it is provided by a library dependency, because library
resources are merged into yours). The only other valid package name
is android, when you want to use a resource from the Android framework.

The type is a type of resource, such as string or drawable, and the name is
the name that identifies the specific resource. Here is an example:

<activity android:icon="@drawable/smallPic" ... >

For more information about how to add resources in your project,


read Providing Resources.

To instead apply a value that's defined in a theme, the first character must
be ? instead of @:
"?[package:]type/name"

String values
Where an attribute value is a string, you must use double backslashes (\\) to
escape characters, such as \\n for a newline or \\uxxxx for a Unicode
character.
Manifest elements reference

The following table provides links to reference documents for all valid elements in
the AndroidManifest.xml file.

<action> Adds an action to an intent filter.


<activity> Declares an activity component.
<activity-alias> Declares an alias for an activity.
<application> The declaration of the application.
<category> Adds a category name to an intent filter.
<compatible-screens> Specifies each screen configuration with which the application is compati

Shri S.V.Patel College of C.S. and B.M. Page 22


405-Mobile Application Development-2

<data> Adds a data specification to an intent filter.


<grant-uri- Specifies the subsets of app data that the parent content provider has perm
permission> access.
<instrumentation> Declares an Instrumentation class that enables you to monitor an applicati
interaction with the system.
<intent-filter> Specifies the types of intents that an activity, service, or broadcast receive
respond to.
<manifest> The root element of the AndroidManifest.xml file.
<meta-data> A name-value pair for an item of additional, arbitrary data that can be sup
the parent component.
<path-permission> Defines the path and required permissions for a specific subset of data wit
content provider.
<permission> Declares a security permission that can be used to limit access to specific
components or features of this or other applications.
<permission-group> Declares a name for a logical grouping of related permissions.
<permission-tree> Declares the base name for a tree of permissions.
<provider> Declares a content provider component.
<queries> Declares the set of other apps that your app intends to access. Learn more
guide about package visibility filtering.
<receiver> Declares a broadcast receiver component.
<service> Declares a service component.
<supports-gl-texture> Declares a single GL texture compression format that the app supports.
<supports-screens> Declares the screen sizes your app supports and enables screen compatibil
mode for screens larger than what your app supports.
<uses-configuration> Indicates specific input features the application requires.
<uses-feature> Declares a single hardware or software feature that is used by the applicat

Shri S.V.Patel College of C.S. and B.M. Page 23


405-Mobile Application Development-2

<uses-library> Specifies a shared library that the application must be linked against.
<uses-native-library> Specifies a vendor-provided native shared library that the app must be link
against.
<uses-permission> Specifies a system permission that the user must grant in order for the app
operate correctly.
<uses-permission- Specifies that an app wants a particular permission, but only if the app is i
sdk-23> on a device running Android 6.0 (API level 23) or higher.
<uses-sdk> Lets you express an application's compatibility with one or more versions
Android platform, by means of an API level integer.

Example manifest file

The XML below is a simple example AndroidManifest.xml that declares two


activities for the app.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0"
package="com.example.myapp">

<!-- Beware that these values are overridden by the build.gradle file -->
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="26" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<!-- This name is resolved to com.example.myapp.MainActivity


based upon the package attribute -->
<activity android:name=".MainActivity">
<intent-filter>

Shri S.V.Patel College of C.S. and B.M. Page 24


405-Mobile Application Development-2

<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>

2. R.java File

Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool)


that contains resource IDs for all the resources of res/ directory.

If you create any component in the activity_main.xml file, id for the corresponding
component is automatically created in this file. This id can be used in the activity
source file to perform any action on the component.

Note: If you delete R.jar file, android creates it automatically.

Android R .java is a class that contain definitions for all the resources a specific
application that you are building. Every resource that is used in you application
will have its id in the android r .java file.

Android R with example:

Suppose you drag a simple plain text view into the main screen of your main-
activity.xml now this plain text view will have its resource id in the android R.java
file. In the same if you look at the coding given below you will see resource ids for
different components, such as icon, texts, themes etc.

This class contain two types of members:

1) Static final classes

2) Static final integers


Shri S.V.Patel College of C.S. and B.M. Page 25
405-Mobile Application Development-2

R.java file is automatically generated by aapt(Android Asset Packaging


Tool).User is not supposed to change this; you change this it will be erased as it is
auto generated every time.

Android R.java Path: /gen/com/foo/R.java

Let's see the android R.java file. It includes a lot of static nested classes such as
menu, id, layout, attr, drawable, string etc.

/* AUTO-GENERATED FILE. DO NOT MODIFY.


*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/

package com.example.helloandroid;

public final class R {


public static final class attr {

Shri S.V.Patel College of C.S. and B.M. Page 26


405-Mobile Application Development-2

}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int menu_settings=0x7f070000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int activity_main=0x7f060000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int hello_world=0x7f040001;
public static final int menu_settings=0x7f040002;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

Theme customizations available in newer API levels can go in


res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.

Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.

API 11 theme customizations can go here.

Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.

API 14 theme customizations can go here.


*/
public static final int AppBaseTheme=0x7f050000;

Shri S.V.Patel College of C.S. and B.M. Page 27


405-Mobile Application Development-2

/** Application theme.


All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f050001;
}
}
Next

1.2 Android Widgets (UI)


 Widgets display glanceable information of an app's most important data
and functionality.
Types
 Widgets display your app’s new and interesting content in a consolidated
form on a mobile home screen. They link to richer detail within the app.
 Users can move and, if supported, resize widgets across their home screen
panels.
1. Information widgets
 Information widgets display a few elements of importance to a user and
track how that information changes over time, such as weather or sports
scores. Tapping the widget launches the associated app into a detail screen.

2. Collection widgets
 Collection widgets display multiple elements of the same type, such as a
collection of articles from a news app. They focus on two interactions:
 Browsing a collection
 Opening an element’s detail screen

Shri S.V.Patel College of C.S. and B.M. Page 28


405-Mobile Application Development-2

 Collection widgets can scroll vertically.

3. Control widgets

 Control widgets display frequently used functions. These functions may be


triggered from the home screen without opening the app. For example,
music app widgets allow the user to play, pause, or skip music tracks from
outside the music app.

Shri S.V.Patel College of C.S. and B.M. Page 29


405-Mobile Application Development-2

 Control widgets may or may not progress to a detail screen.

4. Hybrid widgets
 Many widgets are hybrids that combine elements of the different types
above. Center your widget around one of these types and add elements of
others as needed.

 A hybrid music player widget combines a control widget with elements of


an information widget. The result keeps the user informed about which
track is currently playing.

Shri S.V.Patel College of C.S. and B.M. Page 30


405-Mobile Application Development-2

5. App widgets
Miniature application views that can be embedded in other applications
Related linkarrow_downward

Behaviour
 Scrolling
 List or grid-based collection widgets usually expand or contract the vertical
scrolling area. Regardless of the widget's size, the user can still scroll all
elements...
1. Scrollable widgets
 List or grid-based collection widgets usually expand or contract the vertical
scrolling area. Regardless of the widget's size, the user can still scroll all
elements into view.
 Determine how much of your app's information should surface. For smaller
widget sizes, concentrate on the essential and then add more contextual
information as the widget grows.
2. Non-scrollable widgets
 Information widgets are not scrollable. All content and layout must
dynamically fit into the size selected by the user.
 Resizing
 Resizing allows users to adjust the height or width of a widget. This
allows users to influence the layout of widgets on home panels.
Your.
 Resizing allows users to adjust the height or width of a widget. This
allows users to influence the layout of widgets on home panels.Your
app may be completely resizable or constrained to horizontal or
vertical size changes.

Shri S.V.Patel College of C.S. and B.M. Page 31


405-Mobile Application Development-2

 A long press and subsequent release sets resizable widgets into resize
mode. Users can use the drag handles or the widget corners to set the
desired size.
 Responsive resizing
 Widgets should accommodate different spacing requirements across
devices, including cell number, size, and spacing variations.

 Navigation
 Your widgets should provide navigation links to frequently used
areas of your app, including:
 Your widgets should provide navigation links to frequently used
areas of your app, including:
 Functions that allow the user to create new content, such as a new
document or message
 Access to the top level of your app

 Configuring
 Once placed on a home screen panel, Android widgets display their
configuration choices. Configuration should: Once set up, widgets do
not typically show a "Setup" or...
 Once placed on a home screen panel, Android widgets display their
configuration choices.
 Configuration should:
 Present no more than 2-3 configuration elements
 Present choices using dialogs, rather than full-screen, to retain the
user's context
 Once set up, widgets do not typically show a "Setup" or
"Configuration" button.

1.2.1 Default and Custom Checkbox


 Android Custom Checkbox
 Android provides facility to customize the UI of view elements
rather than default.

Shri S.V.Patel College of C.S. and B.M. Page 32


405-Mobile Application Development-2

 You are able to create custom Checkbox in android. So, you can add
some different images of checkbox on the layout.
 Example of Custom Checkbox

 In this example, we create both default as well as custom checkbox.


Add the following code in activity_main.xml file.
activity_main.xml

File: activity_main.xml

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


<RelativeLayout 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.customcheckbox.MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="25dp"
android:text="Default Check Box"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New CheckBox"
android:id="@+id/checkBox"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"

Shri S.V.Patel College of C.S. and B.M. Page 33


405-Mobile Application Development-2

android:layout_marginTop="46dp" />

<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New CheckBox"
android:id="@+id/checkBox2"
android:layout_below="@+id/checkBox"
android:layout_alignLeft="@+id/checkBox"
android:layout_alignStart="@+id/checkBox" />

<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="200dp"
android:background="#B8B894"
android:id="@+id/viewStub" />

<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox 1"
android:id="@+id/checkBox3"
android:button="@drawable/customcheckbox"
android:layout_below="@+id/viewStub"
android:layout_centerHorizontal="true"
android:layout_marginTop="58dp" />

<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox 2"
android:id="@+id/checkBox4"
android:button="@drawable/customcheckbox"
android:layout_below="@+id/checkBox3"
android:layout_alignLeft="@+id/checkBox3"
android:layout_alignStart="@+id/checkBox3" />

Shri S.V.Patel College of C.S. and B.M. Page 34


405-Mobile Application Development-2

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="25dp"
android:text="Custom Check Box"
android:id="@+id/textView"
android:layout_alignTop="@+id/viewStub"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Checked"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />

</RelativeLayout>

Now implement a selector in another file (checkbox.xml) under drawable folder which customizes the
checkbox.

checkbox.xml

File: checkbox.xml

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


<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/checked" />
<item android:state_checked="false" android:drawable="@drawable/unchecked"/>
</selector>

Activity class

File: MainActivity.java

package example.javatpoint.com.customcheckbox;

Shri S.V.Patel College of C.S. and B.M. Page 35


405-Mobile Application Development-2

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 MainActivity extends AppCompatActivity {


CheckBox cb1,cb2;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cb1=(CheckBox)findViewById(R.id.checkBox3);
cb2=(CheckBox)findViewById(R.id.checkBox4);
button=(Button)findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuilder sb=new StringBuilder("");

if(cb1.isChecked()){
String s1=cb1.getText().toString();
sb.append(s1);
}

if(cb2.isChecked()){
String s2=cb2.getText().toString();
sb.append("\n"+s2);

}
if(sb!=null && !sb.toString().equals("")){
Toast.makeText(getApplicationContext(), sb, Toast.LENGTH_LONG).show();

}
else{

Shri S.V.Patel College of C.S. and B.M. Page 36


405-Mobile Application Development-2

Toast.makeText(getApplicationContext(),"Nothing Selected", Toast.LENGTH_LO


NG).show();
}

});
}
}
Output

Shri S.V.Patel College of C.S. and B.M. Page 37


405-Mobile Application Development-2

Shri S.V.Patel College of C.S. and B.M. Page 38


405-Mobile Application Development-2

1.2.2 Dynamic and Custom RadioButton

 Android Dynamic RadioButton


 Instead of creating RadioButton through drag and drop from palette, android
also facilitates you to create it programmatically (dynamically). For creating
dynamic RadioButton,
 we need to use android.view.ViewGroup.LayoutParams which configures
the width and height of views and
implements setOnCheckedChangeListener() method of RadioGroup class.

Shri S.V.Patel College of C.S. and B.M. Page 39


405-Mobile Application Development-2

Example of Dynamic RadioButton

Let's see an example of Dynamic RadioButton.

activity_main.xml

File: activity_main.xml

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


<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/relativeLayout"
tools:context="com.example.test.dynamicradiobutton.MainActivity">

</RelativeLayout>

Activity class

File: MainActivity.java

package com.example.test.dynamicradiobutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


RadioGroup rg;
RelativeLayout rl;

Shri S.V.Patel College of C.S. and B.M. Page 40


405-Mobile Application Development-2

RadioButton rb1,rb2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

rg = new RadioGroup(this);
rl = (RelativeLayout) findViewById(R.id.relativeLayout);
rb1 = new RadioButton(this);
rb2 = new RadioButton(this);

rb1.setText("Male");
rb2.setText("Female");
rg.addView(rb1);
rg.addView(rb2);
rg.setOrientation(RadioGroup.HORIZONTAL);

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int)


LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
params.leftMargin =150;
params.topMargin = 100;

rg.setLayoutParams(params);
rl.addView(rg);

rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) findViewById(checkedId);
Toast.makeText(getApplicationContext(),radioButton.getText(),Toast.LENGT
H_LONG).show();
}
});
}
}

Shri S.V.Patel College of C.S. and B.M. Page 41


405-Mobile Application Development-2

Shri S.V.Patel College of C.S. and B.M. Page 42


405-Mobile Application Development-2

 Android Custom RadioButton

Rather than default user interface of android RadioButton, we can also implement
a custom radio button. Custom RadioButton makes user interface more attractive.

Example of Custom RadioButton

Let's see an example of custom RadioButton.

activity_main.xml

File: activity_main.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"

Shri S.V.Patel College of C.S. and B.M. Page 43


405-Mobile Application Development-2

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.test.customradiobutton.MainActivity">

<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:textSize="25dp"
android:text="Customized Radio Buttons" />

<!-- Customized RadioButtons -->

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

<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"

Shri S.V.Patel College of C.S. and B.M. Page 44


405-Mobile Application Development-2

android:button="@drawable/custom_radio_button"
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:button="@drawable/custom_radio_button"
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>

custom_radio_button.xml

Now implement a selector in another file (custom_radio_button.xml) in drawable


and place two different checked and unchecked button images.

File: checkbox.xml

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

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_checked="true" android:drawable="@drawable/check


edradiobutton" />

Shri S.V.Patel College of C.S. and B.M. Page 45


405-Mobile Application Development-2

<item android:state_checked="false" android:drawable="@drawable/unche


kedradiobutton" />

</selector>

Activity class

File: MainActivity.java

package com.example.test.customradiobutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


Button button;
RadioButton genderradioButton;
RadioGroup radioGroup;
@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();

Shri S.V.Patel College of C.S. and B.M. Page 46


405-Mobile Application Development-2

}
else{
Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LENGTH
_SHORT).show();
}

}
}

Output

Shri S.V.Patel College of C.S. and B.M. Page 47


405-Mobile Application Development-2

1.2.3 Spinner, AlterDialog

 Spinner
 In Android, Spinner provides a quick way to select one value from a set of
values. Android spinners are nothing but the drop down-list seen in other
programming languages. In a default state, a spinner shows its currently
selected value. It provides a easy way to select a value from a list of values.

 In Simple Words we can say that a spinner is like a combo box of AWT or
swing where we can select a particular item from a list of items. Spinner is a
sub class of AsbSpinner class.
 Spinner is associated with Adapter view so to fill the data in spinner we
need to use one of the Adapter class.
Here is the XML basic code for Spinner:

<Spinner
android:id="@+id/simpleSpinner "
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

 Important Note: To fill the data in a spinner we need to


implement an adapter class. A spinner is mainly used to display only text
field so we can implement Array Adapter for that. We can also use Base
Adapter and other custom adapters to display a spinner with more
customize list. Suppose if we need to display a textview and a imageview in
Shri S.V.Patel College of C.S. and B.M. Page 48
405-Mobile Application Development-2

spinner item list then array adapter is not enough for that. Here we have to
implement custom adapter in our class. Below image of Spinner and
Custom Spinner will make it more clear.

 ArraryAdapter:
 An adapter is a bridge between UI component and data source that helps
us to fill data in UI component. It holds the data and send the data to
adapter view then view can takes the data from the adapter view and
shows the data on different views like as list view, grid view, spinner.
Whenever you have a list of single items which is backed by an array, you
can use Array Adapter.
Here is code of ArrayAdapter in Android:

ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

 For more details read ArrayAdapter Tutorial as here we will use it in the
below example to explain how Spinner is created in Android.

Shri S.V.Patel College of C.S. and B.M. Page 49


405-Mobile Application Development-2

Example of Spinner In Android Studio:


Example
1: Below is the example in which we display a list of bank names in a spinner and
whenever you select an item the value will be displayed using toast on Mobile screen.
Below is the final output and code:
Download Code ?

Step 1: Create a new project in Android Studio and name it SpinnerExample.


Select File -> New -> New Project ->. Fill the forms and click "Finish" button.

Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code.
Here we will create a Spinner inside Relative Layout.

<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"

Shri S.V.Patel College of C.S. and B.M. Page 50


405-Mobile Application Development-2

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />

</RelativeLayout>

Step 3: Now open app-> java -> package -> MainActivity.java and add the following
code. Here we will use ArrayAdapter to fill the data in Spinner. Also we are using Toast
to display when the item in Spinner is selected.

package example.abhiandriod.spinnerexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements


AdapterView.OnItemSelectedListener{

String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Shri S.V.Patel College of C.S. and B.M. Page 51


405-Mobile Application Development-2

setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the bank name list


ArrayAdapter aa = new
ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}

//Performing action onItemSelected and onNothing selected


@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position],
Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
}

Output:
Now the run the program in Emulator and you will see options to choose among bank
names present inside drop down list. You will also see Toast message displaying on the
screen when you will select the particular bank.

Shri S.V.Patel College of C.S. and B.M. Page 52


405-Mobile Application Development-2

 AlterDialog
 Alert Dialog in an android UI prompts a small window to make decision on
mobile screen. Sometimes before making a decision it is required to give an alert
to the user without moving to next activity. To solve this problem alert dialog
came into practise. For example you have seen this type of alert when you try to
exit the App and App ask you to confirm exiting.

AlertDialog.Builder Components Used In Alert Dialog


 AlertDialog.Builder is used to create an interface for Alert Dialog in Android
for setting like alert title, message, image, button, button onclick functionality etc.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

Shri S.V.Patel College of C.S. and B.M. Page 53


405-Mobile Application Development-2

Below are the components of Alert Dialog:


1. setTitle(CharSequence title) – This component is used to set the title of the alert
dialog. It is optional component.

// Setting Alert Dialog Title


alertDialogBuilder.setTitle("Confirm Exit..!!!");

2. setIcon(Drawable icon) – This component add icon before the title. You will need to
save image in drawable icon.

// Icon Of Alert Dialog


alertDialogBuilder.setIcon(R.drawable.question);

3. setMessage(CharSequence message) – This component displays the required


message in the alert dialog.

// Setting Alert Dialog Message


alertDialogBuilder.setMessage("Are you sure,You want to exit");

Shri S.V.Patel College of C.S. and B.M. Page 54


405-Mobile Application Development-2

4. setCancelable(boolean cancelable) – This component has boolean value i.e


true/false. If set to false it allows to cancel the dialog box by clicking on area outside the
dialog else it allows.

alertDialogBuilder.setCancelable(false);

5. setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) –


This component add positive button and further with this user confirm he wants the
alert dialog question to happen.

alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});

Shri S.V.Patel College of C.S. and B.M. Page 55


405-Mobile Application Development-2

6. setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) –


This component add negative button and further with this user confirm he doesn’t
want the alert dialog question to happen.

alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"You clicked over
No",Toast.LENGTH_SHORT).show();
}
});

7. setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener) –


This component simply add a new button and on this button developer can set any
other onclick functionality like cancel button on alert dialog.

alertDialogBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener()


{
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"You clicked
on Cancel",Toast.LENGTH_SHORT).show();
}
});

Alert Dialog Example In Android Studio


Below is the example of Alert Dialog in which the functionality of Alert Dialog is defined
over button click. In this example we have used a simple button and on that button click
the alert dialog window will appear.
Below you can download code, see final output and step by step explanation of Alert
Dialog example in Android Studio.
Download Code

Shri S.V.Patel College of C.S. and B.M. Page 56


405-Mobile Application Development-2

Step 1: Create a new project and name it AlertDialogExample.


Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
Here we add the button UI on click of which alert dialog will appear. We also
used textview for asking user to click on button.

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.alertdialogexample.MainActivity">

Shri S.V.Patel College of C.S. and B.M. Page 57


405-Mobile Application Development-2

<Button
android:text="@string/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:onClick="exit"
android:textStyle="normal|bold"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="131dp"/>

<TextView
android:text="@string/click_over_button_to_exit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="68dp"
android:id="@+id/textView2"
android:layout_above="@+id/button"
android:layout_centerHorizontal="true"
android:textSize="18sp"
android:textStyle="normal|bold"
android:gravity="center" />
</RelativeLayout>

Step 3 : Now open app -> java -> package -> MainActivity.java and add the below code.
In this step firstly AlertDialog.Builder is used to create a interface like setting alert title,
message, image, button, button onclick functionality etc.
Important Note: Add a image to the drawable folder before setting the alert dialog icon.

package com.example.alertdialogexample;

import android.content.DialogInterface;

Shri S.V.Patel College of C.S. and B.M. Page 58


405-Mobile Application Development-2

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void exit(View view){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// Setting Alert Dialog Title
alertDialogBuilder.setTitle("Confirm Exit..!!!");
// Icon Of Alert Dialog
alertDialogBuilder.setIcon(R.drawable.question);
// Setting Alert Dialog Message
alertDialogBuilder.setMessage("Are you sure,You want to exit");
alertDialogBuilder.setCancelable(false);

alertDialogBuilder.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});

alertDialogBuilder.setNegativeButton("No", new
DialogInterface.OnClickListener() {

Shri S.V.Patel College of C.S. and B.M. Page 59


405-Mobile Application Development-2

@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"You clicked over
No",Toast.LENGTH_SHORT).show();
}
});
alertDialogBuilder.setNeutralButton("Cancel", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"You clicked
on Cancel",Toast.LENGTH_SHORT).show();
}
});

AlertDialog alertDialog = alertDialogBuilder.create();


alertDialog.show();
}
}

Output:
Now run the App and click on the button. The alert dialog will appear asking user to
confirm if he wants to exit App. If user click on ‘No’, he remains in the App and if he click
on ‘Yes’ the user will get exit from the App.

Shri S.V.Patel College of C.S. and B.M. Page 60

You might also like