- Android — Event Handling
- Event Listeners & Event Handlers
- Event Listeners Registration
- Touch Mode
- Focus
- onTouchEvent()
- Event Handling Examples
- Event Listeners Registration Using an Anonymous Inner Class
- Exercise
- Basic Event Listeners
- Android Input Events (Event Listeners, Event Handling)
- Android Event Listeners
- Android Event Listeners Registration
- Android Event Handlers
- Android Input Events Example
- activity_main.xml
- MainActivity.java
- Output of Android Input Events Example
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. You can capture these events in your 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 | |||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
onClick() |
Step | Description |
---|---|
1 | You will use Android studio IDE to create an Android application and name it as myapplication under a package com.example.myapplication as explained in the Hello World Example chapter. |
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. |
Following is the content of the modified main activity file src/com.example.myapplication/MainActivity.java. This file can include each of the fundamental lifecycle methods.
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo
Following will be the content of res/values/strings.xml to define two new constants −
Following is the default content of AndroidManifest.xml −
Let’s try to run your myapplication application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Now you try to click on two buttons, one by one and you will see that font of the Hello World text will change, which happens because registered click event handler method is being called against each click event.
Exercise
I will recommend to try writing different event handlers for different event types and understand exact difference in different event types and their handling. Events related to menu, spinner, pickers widgets are little different but they are also based on the same concepts as explained above.
Источник
Basic Event Listeners
Event Listening in Android development is largely centered around the View object.
Any View (Button, TextView, etc) has many event listeners that can be attached using the setOnEvent pattern which involves passing a class that implements a particular event interface. The listeners available to any View include:
- setOnClickListener — Callback when the view is clicked
- setOnDragListener — Callback when the view is dragged
- setOnFocusChangeListener — Callback when the view changes focus
- setOnGenericMotionListener — Callback for arbitrary gestures
- setOnHoverListener — Callback for hovering over the view
- setOnKeyListener — Callback for pressing a hardware key when view has focus
- setOnLongClickListener — Callback for pressing and holding a view
- setOnTouchListener — Callback for touching down or up on a view
Using Java
In Java Code, attaching to any event works roughly the same way. Let’s take the OnClickListener as an example. First, you need a reference to the view and then you need to use the set method associated with that listener and pass in a class implementing a particular interface. For example:
Alternatively, it is sometimes useful to have your class implement the listener directly, in which case you would add the listener implementation to your class and pass a reference to your class to the set method. For Example:
This pattern works for any of the view-based event listeners.
Using XML
In addition onClick has a unique shortcut that allows the method to specified within the layout XML. So rather than attaching the event manually in the Java, the method can be attached in the view. For example:
Within the Activity that hosts this layout, the following method handles the click event:
In addition to the standard View listeners, AdapterView descendants have a few more key event listeners having to do with their items:
- setOnItemClickListener — Callback when an item contained is clicked
- setOnItemLongClickListener — Callback when an item contained is clicked and held
- setOnItemSelectedListener — Callback when an item is selected
This works similarly to a standard listener, simply implementing the correct AdapterView.OnItemClickListener interface:
This works similarly for the setting up a «long click» where an item is pressed and held down using the OnItemLongClickListener:
Troubleshooting: Item Click Not Firing If the item is more complex and does not seem to be properly responding to clicks after setting up the handler, the views inside the item might be drawing the focus. Check out this stackoverflow post and add the property android:descendantFocusability=»blocksDescendants» to the root layout within the template for the item.
In addition to the listeners described above, there are a few other common listeners for input fields in particular.
- addTextChangedListener — Fires each time the text in the field is being changed
- setOnEditorActionListener — Fires when an «action» button on the soft keyboard is pressed
If you want to handle an event as the text in the view is being changed, you only need to look as far as the addTextChangedListener method on an EditText (or even TextView):
This is great for any time you want to have the UI update as the user enters text.
Another case is when you want an action to occur once the user has finished typing text with the Soft Keyboard. Keep in mind that this is especially useful when you can see the virtual keyboard which is disabled by default in the emulator but can be enabled as explained in this graphic.
First, we need to setup an «action» button for our text field. To setup an «action button» such as a Done button on the soft Keyboard, simply configure your EditText with the following properties:
In particular, singleLine and imeOptions are required for the Done button to display. Now, we can hook into a editor listener for when the done button is pressed with:
This is often great whenever a user needs to type text and then explicitly have an action performed when they are finished. There are many imeOptions for different situations.
Similarly to EditText, many common input views have listeners of their own including NumberPicker has setOnValueChangedListener and SeekBar has setOnSeekBarChangeListener which allow us to listen for changes:
Almost all input views have similar methods available.
Источник
Android Input Events (Event Listeners, Event Handling)
In android, Input Events are used to capture the events, such as button clicks, edittext touch, etc. from the View objects that defined in a user interface of our application, when the user interacts with it.
To handle input events in android, the views must have in place an event listener. The View class, from which all UI components are derived contains a wide range event listener interfaces and each listener interface contains an abstract declaration for a callback method. To respond to an event of a particular type, the view must register an appropriate event listener and implement the corresponding callback method.
For example, if a button is to respond to a click event it must register to View.onClickListener event listener and implement the corresponding onClick() callback method. In application when a button click event is detected, the Android framework will call the onClick() method of that particular view.
Generally, to handle input events we use Event Listeners and Event Handling in android applications to listen for user interactions and to extend a View class, in order to build a custom component.
Android Event Listeners
In android, Event Listener is an interface in the View class that contains a single call-back method. These methods will be called by the Android framework when the View which is registered with the listener is triggered by user interaction with the item in UI.
The following are the call-back methods included in the event listener interface.
Method | Description |
---|---|
onClick() | This method is called when the user touches or focuses on the item using navigation-keys or trackball or presses on the «enter» key or presses down on the trackball. |
onLongClick() | This method is called when the user touches and holds the item or focuses on the item using navigation-keys or trackball and presses and holds «enter» key or presses and holds down on the trackball (for one second). |
onFocusChange() | This method is called when the user navigates onto or away from the item, using the navigation-keys or trackball. |
onKey() | This method is called when the user is focused on the item and presses or releases a hardware key on the device. |
onTouch() | This method is called when the user performs a touch event, including a press, a release, or any movement gesture on the screen. |
onCreateContextMenu() | This method is called when a Context Menu is being built. |
There are many more event listeners available as a part of View class to use it in our android applications.
Android Event Listeners Registration
In android, 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.
Following are the different ways to register event listeners in our android applications.
- By specifying event handlers directly in activity_main.xml file, we can register event listeners
- By using Activity class that implements a listener interface, we can register event listeners
- By using an anonymous class.
Following is the example of registering a Button onClick event listener in android application.
@Override
protected void onCreate(Bundle savedInstanceState) <
….
// Capture button from our layout
Button button = (Button)findViewById(R.id.btnShow);
// Register onClick listener with the below implementation
button.setOnClickListener( btnListener );
….
>
// Anonymous implementation of OnClickListener
private View.OnClickListener btnListener = new View.OnClickListener() <
public void onClick(View v) <
// do something when the button is clicked
>
>;
This is how we can register our event listeners in different ways based on our requirements.
Android Event Handlers
In android, Event Handlers are useful to define several callback methods when we are building custom components from view.
Following are the some of commonly used callback methods for event handling in android applications.
Method | Description |
---|---|
onKeyDown() | This method is called when a new key event occurs. |
onKeyUp() | This method is called when a key up event occurs. |
onTrackballEvent() | This method is called when a trackball motion event occurs. |
onTouchEvent() | This method is called when a touch screen motion event occurs. |
onFocusChanged() | This method is called when the view gains or loses focus. |
Now we will see how to define input Events using Even Listeners and Event Handling with examples in android applications.
Android Input Events Example
Following is the example of defining an input controls Button, TextView in user interface and showing the text in TextView when users click on Button in the android application.
Create a new android application using android studio and give names as InputEventsExample. 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
If you observe above code we created a one Button and TextView control in XML Layout file to show the text in textview when we click on Button.
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 MainActivity.java from \java\com.tutlane.inputeventsexample path and write the code like as shown below.
MainActivity.java
package com.tutlane.inputeventsexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity <
Button btn ;
TextView tView ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
btn = (Button)findViewById(R.id. btnClick );
tView = (TextView)findViewById(R.id. txtResult );
btn .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
tView .setText( «You Clicked On Button» );
>
>);
>
>
If you observe above code we registered our Button click event using setOnClickListener event listener and binding a data to TextView control when we click on button.
Generally, during the launch of our activity, onCreate() callback method will be called by android framework to get the required layout for an activity.
Output of Android Input Events Example
When we run above example using android virtual device (AVD) we will get a result like as shown below
If you observe above result, we are getting binding a text to textview control on button click. This is how we can handle input events in android applications based on our requirements.
Источник