Android callback-based event processing
Abstract: no matter whether it is a desktop or mobile app, the most common problem is that users often need to handle user actions-that is, they need to provide responses to user actions. Event processing is a mechanism that provides responses to user actions.
Android provides a powerful event processing mechanism, including two sets of event processing mechanisms:
**-> Listener-based event processing
-> Callback-based event processing **
Listener-based event processing is usually used and familiar. Here we record the callback-based event processing I am not familiar.
For callback-based event processing models, the event source and event listener are unified, or the event listener disappears completely. When an event is triggered on a GUI component,ComponentThe specific method will be responsible for handling the event.
The callback-based event processing mechanism can be implemented through the custom View class. You can override the event processing method of the View when customizing the View. The following is an implementation class for custom buttons.
Public class MyButton extends Button {public MyButton (Context context, AttributeSet set) {super (context, set) ;}@ Override public boolean onKeyDown (int keyCode, KeyEvent event) {super. onKeyDown (keyCode, event); Log. v ("----", "Callback-based instance"); return true ;}}
In our custom Button, the onKayDown method is rewritten to handle keyboard events on the Button.
When using the MyButton component in an xml file:
Com. caiyun. MyButton is the complete Class Name of the MyButton class. Use the complete class name when using a custom class!
After this definition, you do not need to bind a listener to the button in the java program-because the button itself overwrites the onKeyDown (int keyCode, keyEvent event) method, this means that the button will handle the corresponding event by itself.
Summary: for the event processing model monitored, the event source and event listener are separated. When a specific event occurs on the event source, the event is handed over to the event listener for processing; for callback-based event processing, the event source and event listener are unified. When a specific event is generated by the event sourceEvent itselfResponsible for handling.