Android event Response Model Analysis

Source: Internet
Author: User

Android event Response Model Analysis
Android event Response Processing
I. Overview of android event Response Model

Event response is very important for "Page programs" such as android, because it is closely related to interface programming. Just like Activity provides UI, event response provides specific interface operations.

Now that we understand its importance, let's take a closer look at Android's Event Response Processing. Android event Response Processing is relatively simple. The Android event response methods can be divided into two types:

1. listener-based Event Response Model

2. Callback-based Event Response Model

The two actually have no difference in nature, except that the specific listener is different: one is to bind the specified listener and implement its listening function; one is to override the listener function defined in the View.

The following describes the two event responses in detail.


Ii. listener-based Event Response Model

For Android listener-based event processing, the android interface component binds a specific event listener and implements specific code in the listener.

In the event listening processing model,It mainly involves three types of objects.. (Now, people may think it is complicated to get involved with three types of objects. But please take a look at it. In this case, it is easier to understand it later)

* Even Source )............ Is the component

* Even (event )............ User operations

* Even Listener (event Listener )............ Event listener

When you press a button or click a menu item, this action triggers an event, and the event source is the button or menu item. The corresponding changes generated after the press, such as refreshing the interface, pop-up drop-down box or pop-up Dialog, are all of the functions of your event listener.

The above explanation is believed to be a series of concepts related to event response. Now we can use a specific graph to display these three types of objects.


From this figure, we understand that external operations generate event sources, event sources generate events, and events are passed as parameters to the event processor, that is, the event listener. Then the listener implements the response processing method, and a set of processes will be completed.

After learning about the event listening model, we can know that the events generated by different components (event sources) need to be implemented by different event listeners. Here, the event source (Component) is fixed (at least its parent class is fixed, just a few: Button, ImageView, TextView ......), Events generated by fixed components are certainly fixed, so the event listener is also fixed. The difference is that the specific functions of the event listener may be different, which is the key to the listener.

In this case, different event sources are used to generate different events, and different event listeners are required to listen for these events.Take View as an example. What are the specific event listeners?

* View. OnVClickListener ............ Click Event listener of the event

* View. OnCreateContextMenuListener ............ Create an event listener for the context menu

* View. OnFocusChangeListener ............ Event listener with changed focus

* View. OnKeyListener ............ Button event listener

* View. OnLongClickListener ............ Long-Click Event listener

* View. OnTouchListener ............ Touch screen event listener

Taking View as an example, we introduce several different event listeners. In fact, essentially, event listeners are Java class instances that implement specific interfaces.Now let's take a look at several forms of Event Listeners:

1. Internal class form

2. External form

3. the Activity itself acts as the event listener class

4. Anonymous internal class

5. Bind directly to the tag

I will introduce several forms in detail.

1. Internal class form

Internal class listeners can be reused multiple times. The programming interface is concise and easy to understand.

MyListenermyListener = MyListener();MyButton.setOnClickListener(myListener);MyTextView.setOnClickListener(myListener);……Class MyListener extends View.onClickListener{    onClick(View v)        {               Switch(V.getid())                      Case MyButton:                             ……                      Case MyTextView:                             ……               }}
Because of this, internal class listeners are widely used. A large number of internal classes are used in android source code.

2. Form of external class

Listeners in the form of external classes are rare. Why is this analysis on "crazy android handouts:

1. The event listener is usually a specific gui interface, and defining it as an external class is not conducive to improving the coupling between programs.

2. The external class is actually because of the language requirements. It is not convenient to access the gui components. You need to input a specific control ui control for ease of use. The programming is not concise.

It is also suggested that if an event listener is shared by multiple gui interfaces and the completed task emphasizes the business logic (that is, it has little to do with specific interface components, this case does not emphasize the specific page), you can consider using external classes.


3. the Activity itself serves as the event listener

Public class ActivityListener extends Activity implements OnClickListener {...... @ OverridePublic void onClick (View v) {Specific Implementation }......}
Refer to "crazy android handouts" to use this as a listener. In fact, this is not worth mentioning, because it has no special characteristics, in addition, such writing will make the program complex and difficult to read.

4. Anonymous internal class form

In fact, the form of anonymous internal classes is more comfortable to use, which is mainly compared with internal classes, compared with the most valuable "reuse" function in internal classes. If the listener does not emphasize "reuse", anonymous internal classes are a good choice. In fact, the anonymous internal class in the android project is the most widely used listener form.

MyButton. setOnClickListener (newView. OnCickListener {onClick (View v) {implements a specific listener to respond to events ...... }});

5. Bind directly to the tag

Directly binding the listener to a tag is indeed very simple and directly related to the xml and java statements. However, I personally think that this makes the source code not easy to read, which makes it more troublesome, it is not wise to associate xml with java too much.

 
          
  
 
In the preceding xml file, bind the onclick attribute and name "clickBandler" directly. This name is very important and will be implemented directly in the java source code, then you can respond to this Button.

Public class BindingTag extends Activity {@ Override Publicvoid onCreate (Bundle savedInstanceState) {Super. onCreate (savedInstanceState); setContentView (R. layout. main);} // This is the function that responds to the clickBandler tag publicvoid clickBandler (View source) {// the specific operation of the response ......... }}
Simply put, we can know the listening method in the above five. In fact, the focus is internal and anonymous internal classes. This is the key to listening, And the rest only needs to be understood.

Iii. Callback-based event processing

The callback processing is simple and easy to understand. Compared with the listening event processing, the callback is equivalent to placing the event source and event listener in the same control, in this way, I personally understand that it is more convenient to implement object-oriented, define specific components to respond to specific operations, and classify attributes.

Android provides a callback method for all gui components to handle callback events. The following uses View as an example to describe the callback method:

(View Method for destroying the listener class)

* Boolean onKeyDown (int keyCode, KeyEventevent ).

* Boolean onKeyLongPress (int keyCode, keyEvent event ).

* Boolean onkeyShorcut (int keyCode, keyEvent event); this event is triggered when a keyboard shortcut is used.

* Boolean onkeyUp (int keyCode, keyEventevent) events triggered when you release this key

* Boolean onTouchEvent (MotionEvent event). This method is triggered when a touch screen is triggered on this component.

* Boolean onTrackballEvent (MotionEventevent). This method is triggered when the widget triggers the trackball.

In fact, it is explained that the event processing mechanism of the callback function of the ui control is mainly used to pave the way for custom View Controls. the response event of the custom control is described in detail.Callback event PropagationSo we can see the callback mechanism of the custom View through the propagation of callback events.

Callback event Propagation: Specifically, all callback-based event processing methods have a boolean type return value, which indicates whether the callback function has fully processed the event.

* If the returned value is true, the event is completely processed and will not be propagated;

* If it is false, the event will be further propagated.

This is only a callback-based event propagation, and listening does not seem to have such considerations. The reason is that the callbackInheritance(This is my understanding), the callback function will layer-by-layer feedback whether the event has been handled, and the judgment is based on return true or? False !!

Such a layer-by-layer callback feedback.

Let's see what this example means.

Public class Propagation extends Activity {@ Override public void onCreate (BundlesavedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); Buttonbn = (Button) findViewById (R. id. bn); // bind event listener bn to bn. setOnKeyListener (new OnKeyListener () {@ Override public boolean onKey (View source, intkeyCode, KeyEvent event) {// only process the event if (event. getAction () = KeyEvent. ACTION_DOWN) {Log. v ("-Listener-", "the onKeyDown in Listener");} // returns false, indicating that the event will return true; // ① }});} // Override the onKeyDown method. This method can listen to the event @ Override public boolean onKeyDown (int keyCode, KeyEventevent) {super. onKeyDown (keyCode, event); Log. v ("-Activity-", "the onKeyDown in Activity"); // returns false, indicating that the event is not fully handled and the event still spreads out return false ;}

Based on this example, we can also look at the response sequence of the listener event model and callback event model: we can see from the log that the android system triggers the Bound event listener first, then the Event Callback method is triggered, and then the Activity where the component is located is propagated. This is the basic order of the android event processing model. If one of the event processing functions is called urn true. Then the subsequent response function will not be executed.

Iv. Summary

In fact, we can see from a closer look at the two event processing models. The Listener-based event processing model has great advantages, mainly because it has clear logic, easy to read code, and easy to maintain; in addition, the android event processing mechanism also triggers listener-based events first. After comparison, we fully understand the android event listening model!

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.