Unit-1: Project Structure of Mobile Application
Unit-1: Project Structure of Mobile Application
Unit-1: Project Structure of Mobile Application
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"
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.
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.
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.
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.
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:
Value Description
Unspecified It is the default value. In such case, system chooses the orientation.
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
<Button
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
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;
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
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
AndroidManifest.xml
File: AndroidManifest.xml
<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" />
</manifest>
Output:
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).
File features
The following sections describe how some of the most important characteristics of
your app are reflected in the manifest file.
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":
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.
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.
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>
</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>
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.
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.
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.
GroovyKotlin
android {
defaultConfig {
applicationId 'com.example.myapp'
...
}
}
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:
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:
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:
"@[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:
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.
<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.
<!-- 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">
<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
2. R.java File
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.
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.
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.
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.
package com.example.helloandroid;
}
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.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
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.
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
3. Control widgets
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.
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.
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.
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
File: activity_main.xml
<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"
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" />
<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
Activity class
File: MainActivity.java
package example.javatpoint.com.customcheckbox;
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;
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{
});
}
}
Output
activity_main.xml
File: activity_main.xml
</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;
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);
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();
}
});
}
}
Rather than default user interface of android RadioButton, we can also implement
a custom radio button. Custom RadioButton makes user interface more attractive.
activity_main.xml
File: activity_main.xml
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" />
<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"
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
File: checkbox.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
</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;
radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
}
else{
Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LENGTH
_SHORT).show();
}
}
}
Output
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" />
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:
For more details read ArrayAdapter Tutorial as here we will use it in the
below example to explain how Spinner is created in Android.
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"
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;
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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);
@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.
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.
2. setIcon(Drawable icon) – This component add icon before the title. You will need to
save image in drawable icon.
alertDialogBuilder.setCancelable(false);
@Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
<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;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
@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() {
@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();
}
});
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.