Piglet's Android starter Road Day 4-part 2

Source: Internet
Author: User

Piglet's Android starter Road Day 4-part 2

The processing mechanism of Android event--callback-based event handling mechanism

------------ Reprint Please specify the source--coder-pig


Introduction to this section:

In Part 1 we learned about one of the event-handling mechanisms, the event-handling mechanism based on listening, which is simply

Add a listener for our event source (component), and then when the user triggers the event, give it to the listener to process it, depending on the event

perform different actions; What is the principle of the callback-based event-handling mechanism? Well, there's one more question: you know

What is a method callback? You know? I believe a lot of friends are understanding, but can not say it! Well, with these questions we

Parse the callback event handling mechanism in the Android event handling mechanism!




Learning Roadmap for this section




Body:



What is a callback method?


Text expression:


A: is a function definition and function of a means, a decoupling design idea; in Java callbacks are implemented through interfaces,

As a system architecture, must have its own operating environment, and need to provide users with implementation interfaces, the implementation depends on the customer, so that you can

To achieve the unity of the interface, the implementation of different , the system through the different states "callback" our implementation class, so as to achieve the separation of the interface and implementation !


Simple analogy:


Read the above genteel explanation, the method callback or feel a little vague, here is a simple analogy:

Like what:

You come home from school in Friday, you ask your mother to cook dinner no, your mother said not boiled, and then you tell her:

Mom, I look at the pleasant goat, you cook good food call me ha!

Analysis: you and MOM agreed an interface, you call MOM to cook through this interface, when the rice is cooked, your mother

Again through this interface to feedback you, "Rice cooked!"






an explanation of the event handling mechanism for Android snooping:

Through the above simple analogy, we believe that the callback method has a further understanding of it;

There are two key points in the Android callback event mechanism:



① Custom View

When a user fires an event on a GUI component, the component has its own specific method that is responsible for handling the event

General usage : inherit the basic GUI component and override the component's event handling method, which is the custom view

Note: When you use a custom view in an XML layout, you need to use the fully qualified class name



Callback methods for common view components

Android provides some callback methods for event handling for GUI components, with view as an example, there are several methods

① triggers a screen event on this component: boolean ontouchevent (Motionevent event);

② When a button is pressed on the component: boolean onKeyDown (int keycode,keyevent event);

③ Release a button on the component: boolean onKeyUp (int keycode,keyevent event);

④ Long Press a button on a component: boolean onkeylongpress (int keycode,keyevent event);

⑤ keyboard shortcut event occurs: boolean onkeyshortcut (int keycode,keyevent event);

⑥ trigger Trackball Event on component: boolean ontrackballevent (Motionevent event);

*⑦ when the focus of the component changes, unlike the previous 6 elder brother, this method can only be rewritten in view!

protected void Onfocuschanged (Boolean gainfocus, int direction, Rect previously Focusedrect)



PS: Here to explain what the trackball, but not very useful, in the previous BlackBerry phone can be seen; when we browse the Web

, you can think of the trackball as a mouse, but this operation, we can solve with ontouchevent, and not beautiful enough, so now

Very good, basic use, if you are interested to see, you can press F6 in the simulator can be seen!






code example:

We customize a MyButton class to inherit the button class, and then rewrite the Onkeylongpress method;

The custom view is then invoked through the fully qualified class name in the XML file.



:


A simple button, click the button to trigger the ontouchevent event, when we press the keyboard on the simulator,

Press the trigger OnKeyDownto trigger the onKeyUp event when you leave the keyboard! We look through the Logcat




The code is as follows:

Custom view:Mybutton.java

Package Example.jay.com.mybutton;import Android.content.context;import Android.util.attributeset;import Android.util.log;import android.view.keyevent;import Android.view.motionevent;import android.widget.Button;/** * Created by Administrator on 8/5/2014.    */public class MyButton extends button{private static String TAG = "hehe";    Public MyButton (context context, AttributeSet Attrs) {Super (context, attrs); }//Override keyboard pressed events @Override public boolean onKeyDown (int keycode, keyevent event) {Super.onkeydown (keycode,        event);        LOG.I (TAG, "onkeydown method called");    return true; }//Overrides the event that triggers the keyboard @Override public boolean onKeyUp (int keycode, keyevent event) {Super.onkeyup (Keycode,even        T);        LOG.I (TAG, "onkeyup method called");    return true;        }//component was touched @Override public boolean ontouchevent (Motionevent event) {super.ontouchevent (event);        LOG.I (TAG, "ontouchevent method called");    return true; }}


To invoke a layout file for a custom component:main.xml

<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"/></relativelayout>


Code parsing:

Since we have directly rewritten the button's three callback methods, we do not need to do it in the Java file when the Click event occurs.

The binding of the event listener completes the callback, that is, the component handles the corresponding event, that is, the event is handled by the event source (component) itself!




② Callback-based event propagation



In summary, it is true if the return value of the method depends on whether it is propagated outward or false;


code example:

Mybutton.java:

Package Example.jay.com.mybutton;import Android.content.context;import Android.util.attributeset;import Android.util.log;import android.view.keyevent;import Android.view.motionevent;import android.widget.Button;/** * Created by Administrator on 8/5/2014. */public class MyButton extends button{    private static String TAG = "hehe";    Public MyButton (context context, AttributeSet Attrs) {        Super (context, attrs);    }    Override the keyboard to press the event that is triggered    @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

Package Example.jay.com.mybutton;import Android.support.v7.app.actionbaractivity;import Android.os.Bundle;import Android.util.log;import Android.view.keyevent;import Android.view.view;import Android.widget.Button;public class MyActivity extends Actionbaractivity {@Override protected void onCreate (Bundle savedinstancestate) {SUPER.O        Ncreate (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 listener's OnKeyDown method is called ");            } return false;    }        });        } @Override public boolean onKeyDown (int keycode, keyevent event) {Super.onkeydown (keycode, event);        LOG.I ("hehe", "onkeydown method of activity is called"); Return false; }}


Run:



result analysis, from the above results, we can know that the sequence of propagation is: Listener--->view component callback method--->activity callback method;

If you want to test, you can change the return value to False! Very simple!



Related Article

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.