Mad Module - 2
Mad Module - 2
Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file [Link] that
describes each component of the application and how they interact.
There are following four main components that can be used within an Android application −
1. Activities
2. Services
3. Broadcast Receivers
4. Content Providers
Activities:
An activity represents a single screen with a user interface, in-short Activity performs
actions on the screen. For example, an email application might have one activity that shows
a list of new emails, another activity to compose an email, and another activity for reading
emails. If an application has more than one activity, then one of them should be marked as
the activity that is presented when the application is launched.
Services:
Broadcast Receivers:
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system. For example, applications can also initiate broadcasts to let other applications
know that some data has been downloaded to the device and is available for them to use,
so this is broadcast receiver who will intercept this communication and will initiate
appropriate action.
Content Providers:
A content provider component supplies data from one application to others on request.
Such requests are handled by the methods of the ContentResolver class. The data may be
stored in the file system, the database or somewhere else entirely.
Application program interface (API) is a code for a programmer that they use in their
applications. This code or (API) allows you to add specific functionalities to your application.
In other words, we can say that APIs are the set of protocols and tools used for building
software applications
From the developer's perspective, an Android API (or API Levels) is an integer value that
uniquely recognizes the framework of API revision.
Android 2.3.3 10
Android 2.3 9
Android 2.2 8
Android 2.1 7
Android 2.0.1 6
Android 2.0 5
Android 1.6 4
Android 1.5 3
MAD Module – II
Android 1.1 2
Android 1.0 1
The android platform offers an API that Android applications use to communicate with the
underlying Android system. Android framework API consists of the followings points:
To understand this process better, check out how Google Maps works on apps like Ola, Uber,
Zomato, and Swiggy. This app allows you to track the location of your order using the map
feature. Additionally, these apps do not have their own satellites to track your location
through the map.
These apps don’t access Google Maps data directly because Google adds a layer of security
called the Google Map API.
So, when Swiggy wants to retrieve data, it first talks to the Google Maps API instead of
talking to the Google Maps directly. Therefore, an API can be said to be a messenger that
transfers data from one application to another.
MAD Module – II
Suppose you want to add a new API level to your Android application (using Android Studio
Software). In that case, you must navigate to Appearance & Behaviour > System Settings >
and Android SDK. Once you are at the Android SDK screen, checkmark the box next to the
API levels and their features. After that, click on the "OK" button to apply and make the
changes you have done. It will download and install the selected API on the Android Studio
Platform, which you can use in your application.
Once we setup android development environment using android studio and if we create a
sample application using android studio, our project folder structure will be like as shown
below.
MAD Module – II
The Android project structure on the disk might be differs from the above representation.
To see the actual file structure of the project, select Project from the Project dropdown
instead of Android.
The android app project will contain different types of app modules, source code files, and
resource files. We will explore all the folders and files in the android app.
Java Folder
This folder will contain all the java source code (.java) files which we’ll create during the
application development, including JUnit test code. Whenever we create any new
project/application, by default the class file [Link] will create automatically
under the package name “[Link]” like as shown below.
MAD Module – II
The res (Resources) will contain a different type of folders that are
Manifests Folder
This folder will contain a manifest file ([Link]) for our android application.
This manifest file will contain information about our application such as android version,
access permissions, metadata, etc. of our application and its components. The manifest file
will act as an intermediate between android OS and our application.
Gradle Scripts
In android, Gradle means automated build system and by using this we can define a build
configuration that applies to all modules in our application. In Gradle [Link] (Project),
and [Link] (Module) files are useful to build configurations that apply to all our app
modules or specific to one app module.
Following are the important files which we need to implement an app in android studio.
/apk/res/android"
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="[Link]">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</[Link]>
Following is the default code of [Link] file which is generated by our HelloWorld
application.
package [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
}
}
<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=".MainActivity" >
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
These are the main folders and files required to implement an application in android studio.
If you want to see the actual file structure of the project, select Project from
the Project dropdown instead of Android.
Understanding Activities:
An activity is one screen of an app. In that way the activity is very similar to a window in the
Windows operating system.
The most specific block of the user interface is the activity. An Android app contains
activities, meaning one or more screens.
An activity class is per definition a class in Android. Every application which has UI must
inherit it to create a window.
An activity in Android is a specific combination of XML files and JAVA files. It is basically a
container that contains the design as well as coding stuff.
XML files provide the design of the screen and JAVA files deal with all coding stuff like
handles, what is happening, design files, etc. JAVA files and XML files make your activity
complete.
To make an app we need activities that are bound loosely with each other. In the Android
manifest we can organize the activities in parent-child relationships to aid navigation. The
“main activity” is called the first activity.
MAD Module – II
Example: In social media, e-commerce, and other apps, you see the main activity whenever
you open up that app.
Activities must be declared and their certain attributes must be declared in the manifest so
that we can use the activities in our app. Android manifest is a file that will give you
information about the application.
DECLARE ACTIVITIES
Let’s start by declaring our activity. First, open your manifest file then add an element as a
child of the element.
Example:
<manifest ... >
<application ... >
<activity android:name=".ExampleActivity" />
...
</application ... >
...
</manifest >
seDebugValue(value)
Example:
<activity android:name=".ExampleActivity"
android:icon="@drawable/app_icon">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
MAD Module – II
LIFECYCLE OF ACTIVITY
An activity goes through a number of states. Activity lifecycle in Android manages the
different states of activity, such as when the activity starts or stops, etc. All of these states
are managed by callback methods.
onCreate():- This callback method must be created by you, this is fired when your activity is
created by the system. For example, when you open the app it will call onCreate(), onStart(),
and onResume() methods. These three methods are initiated when you open an app.
MAD Module – II
onStart():- There should always be an onStart() callback after onCreate() finishes. In the
started state users will be able to see the activity but they are not ready for user interaction.
onResume():- In this, activities will be in the foreground and ready for user interaction. You
can understand the use of this callback from this example: “when the user presses the
phone’s answer button it will give onPause() after you end up calling it will again give
onResume()”.
onPause():- This callback occurs when there is a case of another activity starting in front of
the current activity. It is the opposite of onResume(). An example for this callback can be
“when you open the app, that is another app from the notification bar, or open settings
then it will call onPause() and onStop()”.
onStop():- It is the opposite of onStart(). In this case, activity will no longer be visible to the
users.
onRestart():- This occurs when the activity is stopped and before the activity starts again. It
is a less common callback.
onDestroy():- It is opposite of onCreate(). This starts when the system needs to free
memory or when finish() is called. It is used for cleanup which is a very common activity.
It is responsible to protect the application to access any protected parts by providing the
permissions.
It also declares the android api that the application is going to use.
It lists the instrumentation classes. The instrumentation classes provide profiling and other
information. These information are removed just before the application is published etc.
This is the required xml file for all the android application and located inside the root
directory.
<manifest xmlns:android="[Link]
package="[Link]"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
MAD Module – II
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="[Link]" />
</manifest>
The elements used in the above xml file are described below.
<manifest>
manifest is the root element of the [Link] file. It has package attribute that
describes the package name of the activity class.
<application>
application is the sub element of the manifest. It includes the namespace declaration. This
element contains several sub elements that declares the application component such as
activity etc.
The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
<activity>
activity is the subelement of application and represents an activity that must be defined in
the [Link] file. It has many attributes such as label, name, theme, launchMode
etc.
<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.
<action>
It adds an action for the intent-filter. The intent-filter must have at least one action element.
<category>
It adds a category name to an intent-filter.
Android UI Layouts
introduction to the Layout Editor
The Layout Editor appears when you open an XML layout file.
1. Palette: contains various views and view groups that you can drag into your layout.
2. Component Tree: shows the hierarchy of components in your layout.
3. Toolbar: has buttons that configure your layout appearance in the editor and change
layout attributes.
4. Design editor: lets you edit your layout in Design view, Blueprint view, or both.
5. Attributes: has controls for the selected view's attributes.
MAD Module – II
6. View mode: lets you view your layout in either Code , Split ,
or Design modes. Split mode shows the Code and Design windows at the same
time.
7. Zoom and pan controls: control the preview size and position within the editor.
When you open an XML layout file, the design editor opens by default, as shown in figure 1.
To edit the layout XML in the text editor, click the Code button in the top-right corner of
the window. Note that the Palette, Component Tree, and Attributes panels are not
available while editing your layout in Code view.
A View Group act as a base class for layouts and layouts parameters that hold other Views
or View Groups and to define the layout properties. They are generally Called layouts.
MAD Module – II
The Android framework will allow us to use UI elements or widgets in two ways:
Use UI elements in the XML file
Create elements in the Kotlin/JAVA file dynamically
When adding a new layout for your app, first create a default layout file in your project's
default layout/ directory so that it applies to all device configurations. Once you have a
default layout, you can create layout variations, as described in a section on this page, for
specific device configurations, such as for large screens.
Layout Managers (or simply layouts) are said to be extensions of the View Group class. They
are used to set the position of child Views within the UI we are building. We can nest the
layouts, and therefore we can create arbitrarily complex UIs using a combination of layouts.
There is a number of layout classes in the Android SDK. They can be used, modified or can
create your own to make the UI for your Views, Fragments and Activities. You can display your
contents effectively by using the right combination of layouts.
Types of Layouts
1. Constraint Layout
Constraint Layout is a flexible layout that allows views to be positioned using
constraints instead of nesting layouts. It helps in reducing the view hierarchy and improves
performance by a lot. It is the most popular and recommended layout for designing complex
interfaces in modern Android applications.
2. Linear Layout
A Linear Layout aligns each of the view in a single direction either a vertical or
a horizontal manner. A layout in vertical manner has a single column of views, whereas in a
layout in horizontal manner, has a single row of views. It supports a weight attribute for each
view that can control the relative size of each view within the available space. However,
excessive nesting of Linear Layouts can lead to performance issues, so it’s best for
straightforward layouts with a few elements.
MAD Module – II
3. Frame Layout
Frame Layout is a simple layout mainly used to hold a single child view, though multiple views
can be stacked on top of each other. It is commonly used for overlays, fragments, and simple
UI components like image views.
4. Relative Layout
Relative layout allows views to be relative to one another or to the parent layout. This makes
positioning flexible as we can position views to the left, right, top, or bottom of other views.
However after Constraint Layout was introduced, the use of Relative Layout has ceased since
Constraint Layout is much better as handling large UIs.
MAD Module – II
5. Table Layout
Table Layout arranges views in a grid-like format using rows and columns, similar to an HTML
table. It is useful for displaying structured data, such as forms or spreadsheets. Each row
consists of multiple Table Row elements, and views within rows can be assigned specific
column spans.
6. Grid Layout
Introduced in Android 4.0 (API level 14), the Grid Layout is an advanced and more flexible
alternative to Table Layout. It divides the screen into a matrix of rows and columns, allowing
precise placement of elements without needing of nested layouts. It is efficient for creating
grid-based UIs like image galleries or dashboards.
7. Coordinator Layout
Coordinator Layout is an advance layout that provides motion and interactive capabilities
between views. It is mostly used for implementing components like the Collapsing Toolbars,
and swipe-to-dismiss behavior. It allows views to work based on user actions, such as
scrolling, swipe gestures and animations.
MAD Module – II
Each of these layouts is designed to scale to suit the screen size of the host device by avoiding
the use of absolute co-ordinates of the positions or predetermined pixel values. This makes
the app suitable for the diverse set of Android devices.
Android - UI Controls
Input controls are the interactive components in your app's user interface. Android provides
a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars,
check box, zoom buttons, toggle buttons, and many more.
UI Elements
A View is an object that draws something on the screen that the user can interact with and
a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define
the layout of the user interface.
You define your layout in an XML file which offers a human-readable structure for the layout,
similar to HTML. For example, a simple vertical layout with a text view and a button looks like
this −
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>
Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical
user interface for your app.
TextView
1
This control is used to display text to the user.
EditText
2 EditText is a predefined subclass of TextView that includes rich editing
capabilities.
AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except
3
that it shows a list of completion suggestions automatically while the user
is typing.
Button
4 A push-button that can be pressed, or clicked, by the user to perform an
action.
ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the
5
exact location of its children. This shows a button with an image (instead
of text) that can be pressed or clicked by the user.
CheckBox
An on/off switch that can be toggled by the user. You should use check box
6
when presenting users with a group of selectable options that are not
mutually exclusive.
MAD Module – II
ToggleButton
7
An on/off button with a light indicator.
RadioButton
8
The RadioButton has two states: either checked or unchecked.
RadioGroup
9
A RadioGroup is used to group together one or more RadioButtons.
ProgressBar
10 The ProgressBar view provides visual feedback about some ongoing tasks,
such as when you are performing a task in the background.
Spinner
11
A drop-down list that allows users to select one value from a set.
TimePicker
12 The TimePicker view enables users to select a time of the day, in either 24-
hour mode or AM/PM mode.
DatePicker
13
The DatePicker view enables users to select a date of the day.
Create UI Controls
Input controls are the interactive components in your app's user interface. Android provides
a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars,
check box, zoom buttons, toggle buttons, and many more.
As explained in previous chapter, a view object may have a unique ID assigned to it which
will identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/text_id"
To create a UI Control/View/Widget you will have to define a view/widget in the layout file
and assign it a unique ID as follows −
<TextView android:id="@+id/text_id"
MAD Module – II
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>
Then finally create an instance of the Control object and capture it from the layout, use the
following −
Events are the actions performed by the user in order to interact with the application, for
e.g. pressing a button or touching the screen. The events are managed by the android
framework in the FIFO manner i.e. First In – First Out. Handling such actions or events by
performing the desired task is called Event Handling.
There are various other event listeners available which can be used for different
requirements and can be found in the official documentation.
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="100dp"
android:fontFamily="@font/arya_bold"
android:text="DataFlair "
android:textColor="@color/colorPrimaryDark"
android:textSize="50dp" />
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:layout_marginTop="100dp"
android:fontFamily="@font/arya_bold"
android:text="Click Event" />
<TextView
android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#009999"
android:layout_marginLeft="150dp"
android:textSize="20dp"
android:textStyle="bold"
android:layout_marginTop="12dp"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:fontFamily="@font/arya_bold"
android:gravity="center"
android:text="See me!"
android:textColor="#009999"
android:textSize="25dp" />
MAD Module – II
</LinearLayout>
Step 3: After writing the code of [Link]. We will now write the code
for main_activity.java as follows:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import android. [Link];
public class MainActivity extends AppCompatActivity {
Button btn;
TextView tView;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
btn = (Button)findViewById([Link]);
tView = (TextView)findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById([Link]);
[Link]("You've Clicked \n The Event has taken place");
[Link](25);
[Link]([Link]);
[Link]([Link]);
}
});
}
}
Step 4: Now open [Link] in this order – app > src>main>res>values>[Link]
Now, we will click and see how the onClick() method reacts when we click.
A Toast is a feedback message. It takes a very little space for displaying while the overall
activity is interactive and visible to the user. It disappears after a few seconds. It
disappears automatically. If the user wants a permanently visible message,
a Notification can be used. Another type of Toast is custom Toast, in which images can be
used instead of a simple message.
MAD Module – II
Example: Toast class provides a simple popup message that is displayed on the current
activity UI screen (e.g. Main Activity).
Constants of Toast class
Constants Description
Methods Description
public static Toast makeText(Context context, makes the toast message consist of
CharSequence text, int duration) text and time duration
public void setMargin (float horizontalMargin, changes the horizontal and vertical
float verticalMargin) differences
Step-By-Step Implementation
The code for that has been given in both Java and Kotlin Programming Language for
Android.
MAD Module – II
Open the “activity_main.xml” file and add a Button to show the Toast message in
a Constraint Layout. Also, Assign an ID to the button component as shown in the image
and the code below. The assigned ID to the button helps to identify and to use files.
android:id="@+id/id_name"
Here the given ID is Button01 This will make the UI of the Application:
EditText Attributes
Following are the important attributes related to EditText control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change
these attributes are run time.
android:autoText
1 If set, specifies that this TextView has a textual input method and automatically corrects
some common spelling errors.
android:drawableBottom
2
This is the drawable to be drawn below the text.
android:drawableRight
3
This is the drawable to be drawn to the right of the text.
android:editable
4
If set, specifies that this TextView has an input method.
android:text
5
This is the Text to display.
Inherited from [Link] Class −
android:background
1
This is a drawable to use as the background.
android:contentDescription
2
This defines text that briefly describes content of the view.
android:id
3
This supplies an identifier name for this view.
android:onClick
4
This is the name of the method in this View's context to invoke when the view is clicked.
android:visibility
5
This controls the initial visibility of the view.
MAD Module – II
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
eText = (EditText) findViewById([Link]);
btn = (Button) findViewById([Link]);
[Link](new OnClickListener() {
public void onClick(View v) {
String str = [Link]().toString();
Toast msg =
[Link](getBaseContext(),str,Toast.LENGTH_LONG);
[Link]();
}
});
}
}
<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
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" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
MAD Module – II
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="18dp"
android:text="@string/example_edittext" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="130dp"
android:text="@string/show_the_text" />
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text" android:inputType="text"
/>
</RelativeLayout>
Following will be the content of res/values/[Link] to define these new constants –
In android, CheckBox is a two-states button that can be either checked (ON) or unchecked
(OFF) and it will allow users to toggle between the two states (ON / OFF) based on the
requirements.
Generally, we can use multiple CheckBox controls in android application to allow users to
select one or more options from the set of values.
By default, the android CheckBox will be in the OFF (Unchecked) state. We can change the
default state of CheckBox by using android:checked attribute.
In android, we can create CheckBox control in two ways either in the XML layout file or
create it in the Activity file programmatically.
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
Attribute Description
android:padding It is used to set the padding from left, right, top and bottom.
android:onClick It’s the name of the method to invoke when the checkbox clicked.
Create a new android application using android studio and give names as CheckBoxExample.
In case if you are not aware of creating an app in android studio check this article Android
Hello World App.
Now open an activity_main.xml file from \res\layout path and write the code like as shown
below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/chkJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
MAD Module – II
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onCheckboxClicked"/>
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Get Details" />
</LinearLayout>
If you observe above code we created a multiple CheckBox controls and one Button control
in XML Layout file.
Once we are done with the creation of layout with required controls, we need to load the
XML layout resource from our activity onCreate() callback method, for that open
main activity file [Link] from \java\[Link] path and
write the code like as shown below.
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Generally, during the launch of our activity, onCreate() callback method will be called by
android framework to get the required layout for an activity.
This is how we can use CheckBox control in android applications to allow users to select one
or more options based on our requirements.
Android radio button is a widget that can have more than one option to choose from. The
user can choose only one option at a time. Each option here refers to a radio button and all
the options for the topic are together referred to as Radio Group. Hence, Radio Buttons are
used inside a RadioGroup.
For Example:
MAD Module – II
<LinearLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#e0e0e0"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select your favourite wwe SuperStar :: "
android:textColor="#000"
android:textSize="20sp"
android:textStyle="bold" />
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/johnCena"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="true"
android:text="@string/johnCena"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />
<RadioButton
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="false"
MAD Module – II
android:text="@string/randyOrton"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />
<RadioButton
android:id="@+id/romanReigns"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="false"
android:text="@string/romanReigns"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />
<RadioButton
android:id="@+id/goldBerg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="false"
android:text="@string/goldBerg"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />
<RadioButton
android:id="@+id/sheamus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:checked="false"
android:text="@string/sheamus"
android:textColor="#154"
android:textSize="20sp"
android:textStyle="bold" />
</RadioGroup>
<Button
android:id="@+id/submitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#0f0"
android:padding="10dp"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
package [Link];
MAD Module – II
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
johnCena = (RadioButton) findViewById([Link]);
randyOrton = (RadioButton) findViewById([Link]);
goldBerg = (RadioButton) findViewById([Link]);
romanReigns = (RadioButton) findViewById([Link]);
sheamus = (RadioButton) findViewById([Link]);
submit = (Button) findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View v) {
if ([Link]()) {
selectedSuperStar = [Link]().toString();
} else if ([Link]()) {
selectedSuperStar = [Link]().toString();
} else if ([Link]()) {
selectedSuperStar = [Link]().toString();
} else if ([Link]()) {
selectedSuperStar = [Link]().toString();
} else if ([Link]()) {
selectedSuperStar = [Link]().toString();
}
[Link](getApplicationContext(), selectedSuperStar, Toast.L
ENGTH_LONG).show(); // print the value of selected super star
}
});
}
}
<resources>
<string name="app_name">RadioButtonExample</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="randyOrton">Randy Orton</string>
<string name="johnCena">John Cena</string>
<string name="romanReigns">Roman Reigns</string>
<string name="goldBerg">Gold Berg</string>
<string name="sheamus">Sheamus</string>
</resources>
MAD Module – II