Unit - III Event Handling in Android Application
Unit - III Event Handling in Android Application
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:
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
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)
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
5 Run the application to launch Android emulator and verify the result
of the changes done in the aplication.
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
Methods Description
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);
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.
Attribute Description
Example: activity_main.xml
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
➢ Go to MainActivity.java.
➢ Now in the java file create a string array and store the values you want to
display in the list.
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
➢ 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.
Attribute Description
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" />
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"};
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_it
em);
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.
➢ 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.
<uses-permission android:name=”android.permission.PERMISSION_NAME”/>
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" />
android:layout_marginTop="16dp"
android:padding="8dp"
android:layout_below="@id/storage"
android:layout_centerHorizontal="true"/>
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:
Syntax:
ActivityCompat.requestPermissions (MainActivity.this,
permissionArray,
requestCode);
Java File:
// Function to check and request permission
public void checkPermission(String permission, int requestCode)
{
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();
}
}
➢ 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;
@Override
protected void onCreate(Bundle savedInstanceState)
{
togglebutton = (ToggleButton)findViewById(R.id.toggleButton);
textview = (TextView)findViewById(R.id.textView);
}