Android 0 Basics section 33rd: Android Event Handling overview

Source: Internet
Author: User

Through the learning of basic Android components, there is also a little touch of Android event handling, such as button click events, marquee state switching events.

First, the Android event processing

Android provides two ways of handling events: callback-based event handling and listener-based event handling.

    • Listener-based event handling: The main approach is to bind specific event listeners to the Android interface component, which has seen a number of examples of this event handling in the previous section.

    • Callback-based event handling: The main approach is to rewrite the Android component-specific callback method, or rewrite the activity's callback method. Android provides callback methods for event response for most of the interface components, and developers simply rewrite them.

In general, callback-based event processing can be used to handle a number of common events, and callback-based event-handling code is more concise. However, for some specific events, callback-based event handling cannot be used, only listener-based event handling is used.

This issue comes first to learn listening-based event processing, followed by the callback-based event processing, focus on sharing talent show (Shareexpert) to get a first-hand tutorial, you can also add small (jinwenyu2010) to the Android 0 basic introductory Technology Discussion group common progress.

Ii. Overview of event handling based on monitoring

Event processing based on listening is a kind of more "object-oriented" event processing, which mainly involves the following three kinds of objects in the processing model of event listener.

    • Event Source: The place where events occur, usually the individual components, such as buttons, windows, menus, and so on.

    • Event: An event encapsulates a specific thing that occurs on an interface component (usually a single user action). If the program needs to obtain information about the events that occur on the interface component, it is generally obtained through the event object.

    • Event Listener: Responsible for listening to events that occur at the source of the event and responding accordingly to various events.

When a user presses a button or clicks a menu item, these actions fire a corresponding event that triggers an event listener (a special Java object) that is registered on the event source, and the event listener invokes the corresponding event handler (the instance method in the event listener) to respond accordingly.

Each component can specify an event listener for a specific event, and each event listener can listen to one or more event sources. Because a variety of events can occur on the same event source, delegated event handling allows you to delegate all possible events on the event source to different event listeners, and also allows a class of events to be handled using the same event listener.

The Android event processing flow is as follows:

As you can see, the process for listening-based event processing models is as follows:

    1. Set up a listener for an event source (interface component) to listen for user actions.

    2. When the user is working, the listener for the event source is triggered.

    3. The corresponding event object is generated.

    4. Pass the event source object as a parameter to the event listener.

    5. The event listener judges the event object and executes the corresponding event handler (the corresponding event processing method).

The development steps for the listener-based event processing model in Android are as follows.

    1. Gets the normal interface component (event source), which is the object being monitored.

    2. Implements the event listener class, which is a special Java class that must implement a Xxxlistener interface.

    3. The Setxxxlistener method that invokes the event source registers the event listener object with the normal component (the event source).

For these three things, the event source can be any interface component, the developer does not need to participate, the registration listener as long as a line of code, so the key to event programming is to implement the event listener class.

In the listener-based event processing model, event listeners must implement an event listener interface, which provides different listener interfaces for different interface components, often in the form of internal classes. Take the view class as an example, which contains the following internal interfaces.

    • View.onclicklistener: Click the interface that the event listener must implement for the event.

    • View.oncreatecontextmenu Listener: An interface that must be implemented by event listeners that create context menu events.

    • View.onfocuschangelistener: The interface that the event listener of the focus change event must implement.

    • View.onkeylistener: The interface that the event listener for the key event must implement.

    • View.onlongclicklistener: The interface that the event listener for long-press events must implement.

    • View.ontouchlistener: The interface that the event listener for touch events must implement.

With the previous learning, it is known that event listeners are instances of Java classes that implement a particular interface. Implementing event listeners in a program usually has the following forms.

    1. Anonymous inner class form: Creates an event listener object using an anonymous inner class.

    2. Inner class form: Defines the event listener class as the inner class of the current class.

    3. External class Form: Defines an event listener class as an external class.

    4. Activity itself acts as an event listener class: Let activity itself implement listener interfaces and implement event handling methods.

    5. Bind directly to the label form: Define an event-handling method directly in the activity that corresponds to the XML layout file, and then reference the event to be triggered in the layout file.

Iii. using anonymous inner classes as event listeners

Most of the time, event handlers have little reuse value (reusable code is often abstracted as a business logic approach), so most event listeners are used only once, so it is more appropriate to use an anonymous inner class as an event listener. In fact, this form is currently the most widely used form of event listener, which is also used to bind listeners in the previous basic component learning process.

Next, learn Android using an anonymous inner class as an event listener through a simple sample program.

Also using the Widgetsample project, continue to use the Activity_main.xml file in the app/main/res/layout/directory, where the following code snippet is populated:

<?XML version= "1.0" encoding= "Utf-8"?><Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" >    <ButtonAndroid:id= "@+id/button"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Use anonymous inner class to listen for events"/></Relativelayout>

To listen for the button's click event, add a click event listener to it in the Java code, with the following code:

 Packagecom.jinyu.cqkxzsxy.android.widgetsample;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.Toast; Public classMainactivityextendsappcompatactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.event_anonymous_inner_class_layout); //Get interface ComponentsButton Button =(Button) Findviewbyid (R.id.button); //use an instance of an anonymous inner class as an event listenerButton.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (view view) {//Implementing Event HandlingToast.maketext (mainactivity. This, "Received Click event", Toast.length_short). Show ();    }        }); }}

The bold section in the above program creates an event listener object using the anonymous inner class, which is the form of the new listener interface or new event adapter to create an event listener in the form of an anonymous inner class.

Run the program, click the button, you can see the interface effect shown.

The only drawback to using anonymous inner classes as event listener classes is that the syntax of the anonymous inner class is a little tricky, and if the Java Foundation is solid and the syntax of the anonymous inner class is better, it is generally advisable to use the anonymous inner class as the listener class.

Four other forms of listening-based event processing in Android continue to learn in the next phase.

Come here today, if you have any questions welcome message to discuss together, also welcome to join the Android 0 Basic introductory Technical discussion group, grow together!

This article copyright for the public Share talent show (Shareexpert)--Xin 鱻 all, if necessary reprint please contact the author authorized, hereby declare!

Past period Summary share:

Android 0 Basics Introduction 1th: Android's past life

Android 0 Basics Section 2nd: Android system Architecture and application components those things

Android 0 Basics Section 3rd: Bring you up to talk about Android development environment

Android 0 Basics 4th: Installing and configuring the JDK correctly Ko fu the first trick

Android 0 Basics 5th: Use ADT bundles to easily meet the goddess

Android 0 Basics 6th: Configuration Optimization SDK Manager, official dating goddess

Android 0 Basics 7th: Take care of Android simulator and start the Sweet journey

Android 0 Basics 8th: HelloWorld, the starting point for my first trip

Android 0 Basics 9th: Android app, no code can be developed

Android 0 Basics Section 10th: Development IDE Big upgrade, finally ushered in Android Studio

Android 0 Basics Introductory Section 11th: Simple steps to take you to fly, run Android Studio project

Android 0 Basics 12th: Get familiar with the Android studio interface and start selling

Android 0 Basics 13th: Android Studio Configuration optimization to create a development tool

Android 0 Basics 14th: Using high-speed genymotion, stepping into the rocket era

Android 0 Basics Section 15th: Mastering the Android Studio project structure, sailing

Android 0 Basics Section 16th: Android User Interface Development overview

Android 0 Basics Section 17th: TextView Properties and Methods Daquan

Android 0 Basics Section 18th: EditText properties and how to use them

Android 0 Basics section 19th: Button usage explained

Android 0 Basics Section 20th: checkbox and RadioButton Usage Daquan

Android 0 Basics Section 21st: ToggleButton and switch usage Daquan

Android 0 Basics Section 22nd: ImageView's properties and methods Daquan

Android 0 Basics Section 23rd: ImageButton and Zoombutton use Daquan

Android 0 Basics Section 24th: Customize view simple to use to create your own controls

Android 0 Basics Section 25th: Simple and most commonly used linearlayout linear layouts

Android 0 Basics Section 26th: Two alignments, layout_gravity and gravity differ greatly

Android 0 Basics section 27th: Using padding and margin correctly

Android 0 Basics Section 28th: Easy to master relativelayout relative layout

Android 0 Basics 29th: Use tablelayout table layouts

Android 0 Basics 30th: Two minutes master Framelayout frame layout

Android 0 Basics Section 31st: absolutelayout absolute Layout with less

Android 0 Basics Section 32nd: New GridLayout Grid layout

Android 0 Basics section 33rd: Android Event Handling overview

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.