Android for Beginners
About Lesson

In Android, event handling is a fundamental part of building interactive applications. Events are used to represent the actions performed by the user interactions, such as touch, click, scroll, etc. Let’s explore how event handling works in Android.

 

What is an Event?

An event in Android is a single unit of interaction with a user, and it is captured in various controls, like buttons, text fields, etc. Some of the common events include clicks, long clicks, key presses, focus changes, etc.

 

Event Listeners and Event Handlers

An event listener is an interface in the View class that contains a single callback method. These methods will be invoked whenever a certain action occurs. Some of the commonly used event listeners include:

  • OnClickListener: It is invoked when you touch the item, lifting your finger in the same place.
  • OnLongClickListener: It is invoked when you touch and hold the item for a longer duration.
  • OnFocusChangeListener: It is invoked when the focus state of a view changes.
  • OnKeyListener: It is invoked when a hardware key event occurs.

An event handler is the method that gets called when the user interacts with the UI control, triggering the event listened to by the listener.

 

Registering Event Listeners

To make a UI control respond to user interactions, you need to register the appropriate event listener and define the event handler. The event listener can be registered using the setOn<Event>Listener methods.

Here’s an example of registering an OnClickListener for a button:

Button button = (Button) findViewById(R.id.my_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here will be executed when the button is clicked
}
});


Handling Click Events in XML

Android also allows you to specify the event handler directly in the XML layout file using the android:onClick attribute. The method you specify will be called when the view is clicked.

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:onClick="handleClick" />

 

In your Activity, you would define the handleClick method like this:

public void handleClick(View view) {
// Code here will be executed when the button is clicked
}