Android Event Processing model

Source: Internet
Author: User

Event handling is a very important part of Android programming because Android apps generate a lot of various events (actions) during the run, and the application must execute corresponding response codes for those actions, and the way the resulting actions and responses are linked is the event-handling mechanism. The Android platform provides two kinds of event handling mechanisms, namely, listening-based and callback-based patterns.

1. Monitoring-based event processing Model 1.1 components
  • Event Source: The place where the event occurred, such as a button, text box, etc.
  • Event: Event type, expressed through the event object
  • Event Listener: Responsible for listening to some type of event and performing the appropriate action

The listener-based event processing model first needs to create an event listener that listens to a certain type of event, and then registers the event listener with a component, and when an action is taken on the component that can be monitored by the listener, the component produces an event object that represents the action. and pass the event object to the listener. In Android, the generation of event objects and the delivery of event objects does not require programmer intervention, and the system automatically handles this step. What the programmer needs to do is to specify the event source, register the event listener corresponding to an event type on the event source, and rewrite the appropriate processing code.

XML Layout Code

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"        android:layout_width="match_parent"        android:layout_height="match_parent">        <Button            android:id="@+id/btn_click"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Click"        /></RelativeLayout>   

Java code

public class MainActivity extends Activity {    private Button mClickBtn;    // 创建监听器,监听“点击”事件    final View.OnClickListener listener =            new View.OnClickListener() {                @Override                public void onClick(View v) {                    L.d("You click btn_click!");                }            };    @Override    protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    mClickBtn = (Button) findViewById(R.id.btn_click);    // 为mClickBtn组件设置事件类型为‘点击’的监听器    mClickBtn.setOnClickListener(listener);}

}

The code above creates a listener listener in mainactivity that listens for "click" Events and registers the listener with MCLICKBTN in the OnCreate method by Setonclicklistener method.

In the preceding code, the listener is implemented through an anonymous inner class, creates an object of the anonymous inner class, and then registers the object with the event source, in the same way that the listener object can be reused, as compared to creating a new listener (shown below) directly in the location where the listener is set.

mClickBtn.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {        L.d("You click btn_click!");    }});

Attention

  • Generic listeners are implemented through an internal class, because an inner class can access components or fields contained in an external class, whereas a generic listener involves operations on related components or fields in an external class. If implemented through an external class, you also need to pass references to this class, and the code is not very intuitive.
  • In general, the listener does not implement business logic, if the listener does require processing logic, you can encapsulate the logic in the method of the external class, and then invoke the method in the listener (the listener is responsible for simple data presentation or data transfer, the logical processing is implemented in a specialized way, this encoding is more consistent with the object-oriented design principles)
2. Callback-based event processing model

The above-mentioned processing mode based on the listener is a delegate event processing, the event processing is delegated to the listener dedicated to handling the event, and the next discussion of the callback-based processing method is an active event processing mode, that is, the event is handled by the event source itself. From the code implementation, the component to add event processing needs to implement a specific interface and override some methods in the interface, and when the corresponding event occurs, the system will callback the overridden method in that component. As an example,

XML Layout Code

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <org.xiuyuan.androidfundemantal.widget.MyButton        android:id="@+id/btn_click"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Click"        /></RelativeLayout>

Java code

Custom MyButton class public class MyButton extends Button {public MyButton (context context, AttributeSet set) {Super (con    text, set);         }//Set callback function @Override public boolean onKeyDown (int keycode, keyevent event) {Super.onkeydown (keycode, event);        LOG.I ("MyButton", "MyButton OnKeyDown");    return false;    }}public class Mainactivity extends Activity {private Button mclickbtn;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    MCLICKBTN = (Button) Findviewbyid (R.id.btn_click); Set Listener Mclickbtn.setonkeylistener (new View.onkeylistener () {@Override public boolean OnKey (View v, int keycode, keyevent event)                {log.i ("mclickbtn", "Onkeylistener");            return false;    }        }); }//set activity callback function @Override public boolean onKeyDown (int keycode, keyevent event) {SupeR.onkeydown (KeyCode, event);        LOG.I ("Mainactivity", "mainactivity OnKeyDown");    return false; }}

After running the above code, it will print in Logcat:
Onkeylistener
MyButton OnKeyDown
Mainactivity OnKeyDown

That is, the order in which the event is called is: the listener –> the callback function of the component, and when the component callback function returns a value of false, the event continues to propagate upward, so the callback function in Acitivity continues to be called, and if the OnKey method in the listener returns True, The component's callback function is not called.

Android Event Processing 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.