Android Note 24. Android Callback-based event handling mechanism

Source: Internet
Author: User
Tags event listener

If the event listener mechanism is a delegate-type event handler, then the callback mechanism is reversed, and the event source and event listener are unified for the callback-based event-handling model, or the event listener is completely gone . When a user fires an event on a GUI control, the control's own specific method is responsible for handling the event . reprint Please indicate source:http://blog.csdn.net/u012637501( embedded _ small J Sky )
first, the common callback method of the view classin order to use the callback mechanism to handle events that occur on a GUI control, you need to provide the corresponding event-handling method for that component, and Java is a static language, and we cannot dynamically add methods for each object , so we can only inherit the GUI control class, and override the event-handling method of the class to implement . In the Android platform, each view has its own callback method for handling specific events, and we can implement the corresponding events by overriding these callback methods in view.
second, callback-based event processing development method 1. General steps for customizing controls (1) define the class name of your component and have the class inherit the view class or a subclass of an existing view ; (2 ) overrides some methods of the parent class , usually requiring Provides a constructor , the constructor is the basic way to create a custom control. The constructor is called when the Java code creates the control or loads and builds the interface based on the XML layout file, overriding some of the methods of the parent class based on business needs. For example ondraw method, used to implement interface display , other methods are onsizechanged (), OnKeyDown (), onKeyUp () and so on. (3) using a custom component that can be created either through Java code or through an XML layout file, it is important to note that in an XML layout file, the component's label is the complete package name + class name , And not just the original class name. 2. Source Code Combat implementation: Customize a button to override the callback method of its touch. (1) Mybutton.java: Custom Components
Package Com.example.android_event2;import Android.content.context;import Android.util.attributeset;import Android.view.keyevent;import Android.widget.button;import Android.widget.toast;public class MyButton extends Button{  Construction method Public MyButton (context context, AttributeSet Attrs) {  Super (context, attrs);}//Callback method @Override public Boolean OnKeyDown (int keycode, keyevent event) {   Super.onkeydown (keycode, event);   Toast.maketext (GetContext (), "You pressed the number:" +keycode,toast.length_short). Show ();   Return true;//returns True, indicating that the event does not spread outwards}}
(2) layouyt/main.xml
< LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "Vertical" Android: Layout_width= "Match_parent" android:layout_height= "Match_parent" > <!--Method One: Create components in an XML layout file--<com.examp Le.android_event2. MyButton android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_grav Ity= "Center_horizontal" android:text= "Callback Test"/></linearlayout> (3) Mainactivity.java: main activitypackage Com.example.android_event2;import Android.app.activity;import Android.os.bundle;public class MainActivity extends         Activity {@Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main); Method Two: Configure custom components in Java code}} 
Effect Demo:
Source Analysis: Configure custom components in a layout file---->< Full package name. The class name needs to be set for the relevant property/> iii. dissemination of event processing 1. Propagation of event processing based on callback methods Almost all callback-based event-handling methods have a Boolean-type return value that identifies whether the processing method can handle the event fully.    If the callback method that handles the event returns true, indicating that the processing method has fully handled the event, the event is not propagated, and if the callback method that handles the event returns false, indicating that the processing method does not fully handle the event, the event will continue to propagate outwards. for callback event propagation, what happens on a component not only fires the callback method on that component, it also triggers a callback method for the activity of the component (provided that the event is propagated to the activity). 2. Source Code Combatimplementation: Customize a button, rewrite its touch callback method, register the touch event listener for it, and override the touch callback method on the activity where it is located, observing the order of event processing. (1) Mainactivity.java
Package Com.example.android_event2;import Android.app.activity;import Android.os.bundle;import Android.view.keyevent;import Android.view.view;import Android.view.view.onkeylistener;import Android.widget.button;public class Mainactivity extends Activity {@Override protected void onCreate (Bundle savedins        Tancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);        Use the listening mode Button MyButton = (button) Findviewbyid (R.ID.BTN); Mybutton.setonkeylistener (New Onkeylistener () {public boolean onKey (View v, int keycode, keyevent event) {System.out    . println ("The event listener that the component is bound to is triggered");   return false;    }                 });       } @Override public boolean onKeyDown (int keycode, keyevent event) {Super.onkeydown (keycode, event);       System.out.println ("callback method for the activity in which the component is located onkeydown called"); Return false;//returns True, indicating that the event does not spread outwards}}
(2) Mybutton.java
Package Com.example.android_event2;import Android.content.context;import Android.util.attributeset;import Android.view.keyevent;import Android.widget.button;public class MyButton extends button{//construction method public MyButton (  Context context, AttributeSet Attrs) {  Super (context, attrs);}//Callback method @Override public boolean onKeyDown (int keycode, KeyEvent event) {   Super.onkeydown (keycode, event);   System.out.println ("callback method in custom component onkeydown called");   Return false;//returns True, indicating that the event does not spread outwards}}
(3) Layout/main.xml
Package Com.example.android_event2;import Android.content.context;import Android.util.attributeset;import Android.view.keyevent;import Android.widget.button;public class MyButton extends button{//construction method public MyButton (  Context context, AttributeSet Attrs) {  Super (context, attrs);}//Callback method @Override public boolean onKeyDown (int keycode, KeyEvent event) {   Super.onkeydown (keycode, event);   System.out.println ("callback method in custom component onkeydown called");   Return false;//returns True, indicating that the event does not spread outwards}}

Effect Demo:
Source Analysis:the experimental results indicate that when a key is pressed randomly. The first trigger is the event listener that the component binds to, and then the event callback method provided by the component is triggered before it is propagated to the activity where the component resides. If we let any one of the event-handling methods return True, the event will not continue to propagate outward. Iv. binding directly to labelsAndroid provides a mechanism for binding event-handling methods to specified tags directly in the interface layout file . For many Android interface controls, they support attributes such as onclick, Onlongclick, and property values that are a method name that is shaped like the xxx (View Source) method. For example, adding a click event to a button in a layout file is handled as follows:<buttonAn droid:layout_width= "wrap_content" android:layout_heigth= "Wrap_content"android:text= "click Me"android:onclick= "ClickHandler"/> 1. Source Code Combat (1) Mainactivity.java
Package Com.example.android_event3;import Android.app.activity;import Android.os.bundle;import Android.view.View; Import Android.widget.edittext;public class Mainactivity extends Activity {private EditText text;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.main);        Text = (EditText) Findviewbyid (R.id.result);    }    Bind the ClickHandler method directly to the label public    void ClickHandler (View source)    {     Text.settext ("Long live the People's Republic of China!") ");    }}
(2) Layout/main.xml
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation= "Vertical    " Android:layout_width= "Match_parent"    android:layout_height= "match_parent" > <button     android:layout_ Width= "Match_parent"     android:layout_height= "wrap_content"     android:text= "click Me"     android:onclick= " ClickHandler "/> <edittext     android:id=" @+id/result "     android:inputtype=" None "     android:layout_ Width= "Match_parent"     android:layout_height= "Wrap_content"/></linearlayout>
Effect Demo:

Android Note 24. Android Callback-based event handling mechanism

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.