Android's callback-based event processing mechanism

Introduction to this section

In 3.1, we learned about an event processing mechanism in Android—an event processing mechanism based on monitoring. Simply put, it is to add a listener to our event source (component), and then when the user triggers the event, the Let the listener handle it, and perform different operations according to different events; so what is the principle of the callback-based event processing mechanism? Ok, one more question: do you know what a method callback is ? do you know? I believe that many friends know it, but they can't tell it! Well, with these questions, let's analyze the callback event processing mechanism in the android event processing mechanism!


1. What is method callback?

Text expression:

Answer: It is a means to separate the function definition from the function, a design idea of ​​decoupling; in Java, the callback is realized through the interface. As a system architecture, it must have its own operating environment, and it needs to provide The user provides the implementation interface; the implementation depends on the customer, so that the interface can be unified and the implementation is different. The system "calls back" our implementation class in different states, so as to achieve the separation of interface and implementation!

To give a simple example:

For example: when you come home from school on Friday, you ask your mother if the rice is ready, and your mother says it hasn’t been cooked yet; then you tell her: Mom, let me see Pleasant Goat, call me when you are done cooking! Analysis  : You and your mother have agreed on an interface, and you ask your mother to cook the rice through this interface. When the rice is cooked, your mother will feedback to you through this interface, "The rice is cooked"!

2. Detailed explanation of the event processing mechanism of Android callback:

There are two usage scenarios for the callback-based event processing mechanism in Android:

1) Custom view

When the user triggers an event on a GUI component, the component has its own specific method that will be responsible for handling the event. Common usage: inherit the basic GUI component, rewrite the event processing method of the component, that is, customize the view Note: in the xml layout When using a custom view, you need to use the "fully qualified class name"

Callback methods of common View components:

Android provides some callback methods for event processing for GUI components. Taking View as an example, there are the following methods

①Trigger a screen event on the component: boolean  onTouchEvent (MotionEvent event);
②When a button is pressed on the component: boolean  onKeyDown (int keyCode,KeyEvent event);
③When a button on the component is released: boolean  onKeyUp (int keyCode,KeyEvent event);
④When a button of the component is long pressed: boolean  onKeyLongPress (int keyCode,KeyEvent event);
⑤When a keyboard shortcut event occurs: boolean  onKeyShortcut (int keyCode,KeyEvent event);
⑥Triggered on the component Trackball screen event: boolean  onTrackballEvent (MotionEvent event);
*⑦When the focus of the component changes, it is different from the previous 6 methods, this method can only be rewritten in View! protected void  onFocusChanged (boolean gainFocus, int direction, Rect previously FocusedRect)

In addition, here is an explanation of what a trackball is, but it is not very useful. It can be seen on the previous BlackBerry mobile phone; when we browse the web, we can use the trackball as a mouse, but for this operation, we use onTouchEvent It can be solved, and it is not beautiful enough, so it is very good now, basically not used, if you are interested to see it, you can press f6 in the original Android emulator to see it!

Code example:  We customize a MyButton class to inherit the Button class, and then rewrite the onKeyLongPress method; then call the custom view through the fully qualified class name in the xml file

The renderings are as follows:

A simple button, the onTouchEvent event is triggered after the button is clicked, when we press the keyboard on the emulator, the onKeyDown is triggered when we press the button, and the onKeyUp event is triggered when we leave the keyboard! We check through Logcat!

Implementation code:  MyButton.java

public class MyButton extends Button{  
    private static String TAG = "呵呵";  
    public MyButton(Context context, AttributeSet attrs) {  
        super(context, attrs);  
    }  
  
    //Rewrite the event triggered by the keyboard press  
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        super.onKeyDown(keyCode,event);  
        Log.i(TAG, "onKeyDown method is called");  
        return true;  
    }  
  
    //Rewrite the event triggered by the pop-up keyboard  
    @Override  
    public boolean onKeyUp(int keyCode, KeyEvent event) {  
        super.onKeyUp(keyCode,event);  
        Log.i(TAG,"the onKeyUp method is called");  
        return true;  
    }  
  
    // the component is touched  
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
        super.onTouchEvent(event);  
        Log.i(TAG,"the onTouchEvent method is called");  
        return true;  
    }  
} 

layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MyActivity">  
    
    <example.jay.com.mybutton.MyButton  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="button"/>

Code analysis:

Because we directly rewrite the three callback methods of Button, when a click event occurs, we don’t need to bind the event listener in the Java file to complete the callback, that is, the component will process the corresponding event, that is, the event is triggered by the event The source (component) handles itself!


2) Callback-based event propagation:

In summary, whether to propagate outward depends on whether the return value of the method is true or false;

Code example:

public class MyButton extends Button{  
    private static String TAG = "呵呵";  
    public MyButton(Context context, AttributeSet attrs) {  
        super(context, attrs);  
    }  
  
    //Rewrite the event triggered by the keyboard press  
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        super.onKeyDown(keyCode,event);  
        Log.i(TAG, "The onKeyDown method of the custom button is called");  
        return false;  
    }  
}

main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MyActivity">  
  
    <example.jay.com.mybutton.MyButton  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="custom button"  
        android:id="@+id/btn_my"/>  
</LinearLayout>  

MainActivity.java:

public class MyActivity extends ActionBarActivity {  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_my);  
  
        Button btn = (Button)findViewById(R.id.btn_my);  
        btn.setOnKeyListener(new View.OnKeyListener() {  
            @Override  
            public boolean onKey(View v, int keyCode, KeyEvent event) {  
                if(event.getAction() == KeyEvent.ACTION_DOWN)  
                {  
                    Log.i("hehe", "the onKeyDown method of the listener is called");  
                }  
                return false;  
            }  
        });  
    }  
  
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        super.onKeyDown(keyCode, event);  
        Log.i("Hehe", "Activity's onKeyDown method is called");  
        return false;  
    }  
} 

Run the screenshot:

Result analysis: From the above running results, we can know that the order of propagation is:  listener ---> callback method of view component ---> callback method of Activity ;

Guess you like

Origin blog.csdn.net/leyang0910/article/details/131215058