0% found this document useful (0 votes)
68 views14 pages

Unit - III Event Handling in Android Application

Uploaded by

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

Unit - III Event Handling in Android Application

Uploaded by

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

Mobile Application Development Course Code: 4350703

Unit– III
Event Handling in Android Application
Android - Event Handling:
Events are a useful way to collect data about a user's interaction with interactive
components of Applications.
Like button presses or screen touch etc. The Android framework maintains an
event queue as first-in, first-out (FIFO) basis. We can capture these events in our
program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management −
• Event Listeners − An event listener is an interface in the View class that
contains a single callback method. These methods will be called by the
Android framework when the View to which the listener has been registered
is triggered by user interaction with the item in the UI.
• Event Listeners Registration − Event Registration is the process by which
an Event Handler gets registered with an Event Listener so that the handler
is called when the Event Listener fires the event.
• Event Handlers − When an event happens and we have registered an event
listener for the event, the event listener calls the Event Handlers, which is
the method that actually handles the event.
Event Listeners & Event Handlers:

Event Handler Event Listener & Description

OnClickListener()
This is called when the user either clicks or touches or
onClick()
focuses upon any widget like button, text, image etc. You
will use onClick() event handler to handle such event.

OnLongClickListener()
This is called when the user either clicks or touches or
onLongClick()
focuses upon any widget like button, text, image etc. for
one or more seconds. You will use onLongClick() event

VPMP Polytechnic, Computer Department. 7


Mobile Application Development Course Code: 4350703

handler to handle such event.

OnFocusChangeListener()
This is called when the widget looses its focus ie. user
onFocusChange()
goes away from the view item. You will use
onFocusChange() event handler to handle such event.

OnFocusChangeListener()
This is called when the user is focused on the item and
onKey()
presses or releases a hardware key on the device. You will
use onKey() event handler to handle such event.

OnTouchListener()
This is called when the user presses the key, releases the
onTouch()
key, or any movement gesture on the screen. You will use
onTouch() event handler to handle such event.

OnMenuItemClickListener()
This is called when the user selects a menu item. You will
onMenuItemClick()
use onMenuItemClick() event handler to handle such
event.

onCreateContextMenuItemListener()
onCreateContextMenu() This is called when the context menu is being built(as the
result of a sustained "long click)

Event Handling Examples:


Event Listeners Registration Using an Anonymous Inner Class
Here you will create an anonymous implementation of the listener and will be
useful if each class is applied to a single control only and you have advantage to
pass arguments to event handler. In this approach event handler methods can
access private data of Activity. No reference is needed to call to Activity.
But if you applied the handler to more than one control, you would have to cut and
paste the code for the handler and if the code for the handler is long, it makes the
code harder to maintain.

VPMP Polytechnic, Computer Department. 8


Mobile Application Development Course Code: 4350703

Following are the simple steps to show how we will make use of separate Listener
class to register and capture click event. Similar way you can implement your
listener for any other required event type.

Step Description

1 Use Android studio IDE to create an Android application

2 Modify src/MainActivity.java file to add click event listeners and


handlers for the two buttons defined.

3 Modify the detault content of res/layout/activity_main.xml file to


include Android UI controls.

4 No need to declare default string constants.Android studio takes care


default constants.

5 Run the application to launch Android emulator and verify the result
of the changes done in the aplication.

Navigating between Activities using Intent:

Intents could be Implicit, for instance, calling intended actions, and explicit as
well, such as opening another activity after some operations like onClick or
anything else. Below are some applications of Intents:
1. Sending the User to Another App
2. Getting a Result from an Activity
3. Allowing Other Apps to Start Your Activity
Some Important Method of Intent and their Description

Methods Description

This is to launch a new activity or get an existing


Context.startActivity()
activity to be action.

Context.startService() This is to start a new service or deliver instructions

VPMP Polytechnic, Computer Department. 9


Mobile Application Development Course Code: 4350703

Methods Description

for an existing service.

Context.sendBroadcast() This is to deliver the message to broadcast receivers.

Types of Android Intents:


There are two types of intents in android
1. Implicit
2. Explicit

Implicit Intent
Implicit Intent doesn’t specify the component. In such a case, intent provides
information on available components provided by the system that is to be invoked.
For example, you may write the following code to view the webpage.
Syntax:
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.geeksforgeeks.org/"));
startActivity(intent);
For Example: a webpage is going to be opened. As you type the name of your
desired webpage and click on the ‘CLICK’ button. Your webpage is opened.

Explicit Intent
Explicit Intent specifies the component. In such a case, intent provides the external
class to be invoked.
Syntax:
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);

VPMP Polytechnic, Computer Department. 10


Mobile Application Development Course Code: 4350703

For Example: In the given example, there are two activities (FirstActivity, and
SecondActivity). When you click on the ‘GO TO OTHER ACTIVITY’ Button in
the FirstActivity, then you move to the SecondActivity. When you click on the
‘GO TO HOME ACTIVITY’ button in the SecondActivity, then you move to the
first activity. This is getting done through Explicit Intent.

VPMP Polytechnic, Computer Department. 11


Mobile Application Development Course Code: 4350703

Android Listview in Java

Android ListView is a ViewGroup that is used to display the list of items in


multiple rows and contains an adapter that automatically inserts the items into the
list.

XML Attributes of ListView

Attribute Description

A color or drawable to separate list


android:divider
items.

android:dividerHeight Divider’s height.

Reference to an array resource that


android:entries
will populate the ListView.

When set to false, the ListView will


android:footerDividersEnabled not draw the divider before each
footer view.

When set to false, the ListView will


android:headerDividersEnabled not draw the divider before each
header view.

❖ How to add a ListView in an Android App


Step 1: Create a new project

1. Click on File, then New => New Project.

2. Choose “Empty Activity” for the project template.

3. Select language as Java.

4. Select the minimum SDK as per your need.

Step 2: Modify activity_main.xml file

Add a ListView in the activity_main.xml file.

VPMP Polytechnic, Computer Department. 12


Mobile Application Development Course Code: 4350703

Example: activity_main.xml
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

Step 3: Modify MainActivity.java file

➢ Go to MainActivity.java.

➢ Now in the java file create a string array and store the values you want to
display in the list.

➢ Also, create an object of ListView class.

➢ In onCreate() method find Listview by id using findViewById() method.

➢ Create an object of ArrayAdapter using a new keyword followed by a


constructor call.

Example: MainActivity.java
public class MainActivity extends Activity
{
ListView l;
String tutorials[]={ "Algorithms", "Data Structures",
"Languages", "Interview Corner"};

@Override
protected void onCreate(Bundle savedInstanceState)
{
l = findViewById(R.id.list);
ArrayAdapter<String> arr;
arr = new ArrayAdapter<String>(this,
R.layout.support_simple_spinner_dropdown_item,
tutorials);
l.setAdapter(arr);
}
}

Spinner in Android

➢ Android Spinner is a view similar to the dropdown list which is used to


select one option from the list of options.

VPMP Polytechnic, Computer Department. 13


Mobile Application Development Course Code: 4350703

➢ It provides an easy way to select one item from the list of items and it shows
a dropdown list of all values when we click on it.

➢ The default value of the android spinner will be the currently selected value
and by using Adapter we can easily bind the items to the spinner objects.

Different Attributes for Spinner Widget

Attribute Description

android:id Used to specify the id of the view.

Used to the text alignment in the


android:textAlignment
dropdown list.

Used to set the background of the


android:background
view.

android:padding Used to set the padding of the view.

android:visibility Used to set the visibility of the view.

Used to specify the gravity of the view


android:gravity
like center, top, bottom, etc

❖ Example to demonstrate the Spinner


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:

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

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

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

VPMP Polytechnic, Computer Department. 14


Mobile Application Development Course Code: 4350703

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.
public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener
{

String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};

protected void onCreate(Bundle savedInstanceState)


{
//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_it
em);

//Setting the ArrayAdapter data on the Spinner


spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
public void onItemSelected(AdapterView<?> arg0, View arg1, int
position,long id)
{
Toast.makeText(getApplicationContext(), bankNames[position],
Toast.LENGTH_LONG).show();
}
}

VPMP Polytechnic, Computer Department. 15


Mobile Application Development Course Code: 4350703

❖ How to Request Permissions in Android Application?


➢ Starting from Android 6.0 (API 23), users are not asked for permissions at
the time of installation rather developers need to request the permissions at
the run time. Only the permissions that are defined in the manifest file can
be requested at run time.

Types of Permissions
➢ Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the
permission is requested at the installation time at the Google Play Store.

➢ If the user Accepts the permissions, the app is installed. Else the
app installation is canceled.

➢ Run-Time Permissions: If the Android 6 (API 23) or higher, the


permission is requested at the run time during the running of the app.

VPMP Polytechnic, Computer Department. 16


Mobile Application Development Course Code: 4350703

➢ If the user accepts the permissions, then that feature of the app can be used.
Else to use the feature, the app requests permission again.

➢ So, now the permissions are requested at runtime.

➢ In this article, we will discuss how to request permissions in an Android


Application at run time.

Steps for Requesting permissions at run time


Step 1: Declare the permission in the Android Manifest file: In Android,
permissions are declared in the AndroidManifest.xml file using the uses-
permission tag.

<uses-permission android:name=”android.permission.PERMISSION_NAME”/>

➢ Here we are declaring storage and camera permission.

activity_main.xml:
<!--Declaring the required permissions-->
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

Step 2: Modify activity_main.xml file to Add two buttons to request


permission on button click: Permission will be checked and requested on button
click. Open the activity_main.xml file and add two buttons to it.
<!--Button to request storage permission-->
<Button
android:id="@+id/storage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Storage"
android:layout_marginTop="16dp"
android:padding="8dp"
android:layout_below="@id/toolbar"
android:layout_centerHorizontal="true"/>

<!--Button to request camera permission-->


<Button
android:id="@+id/camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Camera"

VPMP Polytechnic, Computer Department. 17


Mobile Application Development Course Code: 4350703

android:layout_marginTop="16dp"
android:padding="8dp"
android:layout_below="@id/storage"
android:layout_centerHorizontal="true"/>

Step 3: Check whether permission is already granted or not. If permission


isn’t already granted, request the user for the permission: In order to use
any service or feature, the permissions are required. Hence we have to ensure
that the permissions are given for that. If not, then the permissions are
requested.

Check for permissions: Beginning with Android 6.0 (API level 23), the user
has the right to revoke permissions from any app at any time, even if the app
targets a lower API level. So to use the service, the app needs to check for
permissions every time.

Syntax:

if(ContextCompat. checkSelfPermission (thisActivity,


Manifest.permission.WRITE_CALENDAR)
!= PackageManager.PERMISSION_GRANTED)
{
// Permission is not granted
}

Request Permissions: When PERMISSION_DENIED is returned from


the checkSelfPermission() method in the above syntax, we need to prompt the
user for that permission.

➢ Android provides several methods that can be used to request permission,


such as requestPermissions().

Syntax:

ActivityCompat.requestPermissions (MainActivity.this,
permissionArray,
requestCode);

➢ Here permissionArray is an array of type String.

Java File:
// Function to check and request permission
public void checkPermission(String permission, int requestCode)
{

VPMP Polytechnic, Computer Department. 18


Mobile Application Development Course Code: 4350703

// Checking if permission is not granted

if (ContextCompat.checkSelfPermission(MainActivity.this,
permission) == PackageManager.PERMISSION_DENIED)
{
ActivityCompat.requestPermissions(MainActivity.this, new String[] {
permission }, requestCode);
}
else
{
Toast.makeText(MainActivity.this, "Permission already
granted", Toast.LENGTH_SHORT).show();
}
}

➢ This function will show a Toast message if permission is already granted


otherwise prompt the user for permission.

❖ How to add Toggle Button in an Android


➢ ToggleButton is basically a stop / play or on/off button with indicator light
indicating the current state of ToggleButton.

➢ ToggleButton is widely used, some examples are on/off audio, Bluetooth,


WiFi, hot-spot etc.

➢ This is a subclass of Composite Button.

➢ ToggleButton allows users to change settings between two states from your
phone’s Settings menu such as turning your WiFi, Bluetooth, etc. on / off.

activity_main.xml:

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="onToggleClick" />
Java File:
public class MainActivity extends Activity
{

ToggleButton togglebutton;
TextView textview;

VPMP Polytechnic, Computer Department. 19


Mobile Application Development Course Code: 4350703

@Override
protected void onCreate(Bundle savedInstanceState)
{
togglebutton = (ToggleButton)findViewById(R.id.toggleButton);
textview = (TextView)findViewById(R.id.textView);
}

public void onToggleClick(View view)


{
if (togglebutton.isChecked())
{
textview.setText("Toggle is ON");
}
else
{
textview.setText("Toggle is OFF");
}
}
}

VPMP Polytechnic, Computer Department. 20

You might also like