Android Basics Getting Started tutorial--3.2 callback-based event handling mechanism

Source: Internet
Author: User

Android Basics Getting Started tutorial--3.2 callback-based event handling mechanism

tags (space delimited): Android Basics Getting Started Tutorial

Introduction to this section

In 3.1 We learned about an event-handling mechanism in Android, 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!

1. What is a method callback?

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!

To give a simple example:

For example: you come home from school in Friday, you ask your mother to cook dinner no, your mother said not boiled, 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 through this interface called Mom Cooking, when the meal is cooked, your mother
Again through this interface to feedback you, "Rice cooked!"

An explanation of the event handling mechanism for the 2.Android callback:

There are two scenarios in which the callback-based event handling mechanism is used in Android:

1) 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

① trigger 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, and the previous 6 different, this method can only be overridden in the view Oh!
protected void onfocuschanged(boolean gainfocus, int direction, Rect previously Focusedrect)

What's more, it explains what a trackball is, but it's not very useful, as you can see on a BlackBerry phone, 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 click on the original Android simulator F6 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.

As follows:

A simple button, click the button to trigger the Ontouchevent event, when we press the keyboard on the simulator,
Press the trigger onkeydown to trigger the onkeyup event when you leave the keyboard! We look through the Logcat!

Implementation code:
Mybutton.java

 Public  class MyButton extends Button{      Private StaticString TAG =" very well"; Public MyButton(context context, AttributeSet attrs) {Super(context, attrs); }//Override keyboard Press to trigger event    @Override       Public Boolean OnKeyDown(intKeyCode, KeyEvent event) {Super. OnKeyDown (Keycode,event); LOG.I (TAG,"The OnKeyDown method is called");return true; }//Rewrite events triggered by the keyboard    @Override       Public Boolean onKeyUp(intKeyCode, KeyEvent event) {Super. OnKeyUp (Keycode,event); LOG.I (TAG,"The OnKeyUp method is called");return true; }//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="按钮"/>  

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!

2) 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:

 Public  class MyButton extends Button{      Private StaticString TAG =" very well"; Public MyButton(context context, AttributeSet attrs) {Super(context, attrs); }//Override keyboard Press to trigger event    @Override       Public Boolean OnKeyDown(intKeyCode, 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   .mybutton   android:layout_width= "wrap_content"  Android:layout_heig Ht= "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 (NewView.onkeylistener () {@Override               Public Boolean OnKey(View V,intKeyCode, KeyEvent event) {if(event.getaction () = = Keyevent.action_down) {LOG.I (" very well","The onkeydown method of the listener is called"); }return false;      }          }); }@Override       Public Boolean OnKeyDown(intKeyCode, KeyEvent event) {Super. OnKeyDown (KeyCode, event); LOG.I (" very well","The onkeydown method of activity is called");return false; }  }

Run:

Results Analysis:
From the above running results, we can know that the order of propagation is:
callback method for theactivity, listener -and-View component callback method;

Summary of this section

This section explains the callback-based event handling mechanism in the Android event handling mechanism! The core is the order of event propagation.
The listener takes precedence, then goes to the view component itself, and finally to the activity; The return value false continues to propagate, true terminates propagation!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Basics Getting Started tutorial--3.2 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.