Android Event distribution detailed (i)--view event distribution

Source: Internet
Author: User

Mainactivity as follows:
Package Cc.cv;import Android.os.bundle;import Android.view.motionevent;import android.view.view;import Android.view.view.onclicklistener;import Android.view.view.ontouchlistener;import Android.widget.Button;import Android.widget.imageview;import android.app.activity;/** * Demo Description: * View Event Distribution * * During the event distribution of the view, it mainly involves dispatchtouchevent () and Ontouch () and ontouchevent () * * Dispatchtouchevent () Returning True or false indicating whether to continue the event distribution * OnTouch () returns TRUE or false to indicate whether the event is consumed * ontouchevent () in the main processing click event * Event distribution starts from Dispatchtouchevent (). * Method Dispatchtouchevent () The return value is true when the continuation event is distributed, and the return value of FALSE indicates termination event distribution. * The source code is as follows: * * Public boolean dispatchtouchevent (Motionevent event) {* IF (montouchlistener!= null&& (Mviewflags & Amp Enabled_mask) ==enabled&&montouchlistener.ontouch (this,event)) {* return true; *} * return Ontoucheve NT (event); *} * * The return value of this method has two cases: * * 1 returns True if condition is met. Note the three judgments of the IF condition. * 1.1 Montouchlistener Not equal to NULL * 1.2 Current control is enable * 1.3 call Montouchlistener.ontouch (this,event)Results returned * The first two conditions there is nothing more to say, the main look at the third condition: * in OnTouch (View V, motionevent event) a series of action_down,action_move,action_up will be processed. * The Ontouch () method returns True to indicate that the event has been consumed and returns false to indicate that the event was not consumed. * For example, returns True when processing Action_down to continue distributing action_move events * such as returning true when processing action_move to continue distributing action_up events * For example, return f when processing Action_down Alse, then the subsequent action_move,action_up will not continue to distribute. * We can't capture the two ACTION of action_move,action_up in the code. * 2 If the IF condition is not satisfied, then proceed to return the execution result of the Ontouchevent (event). * * * * from the source of the dispatchtouchevent () can also be seen * OnTouch (this,event) and Ontouchevent (event) Difference and relationship: * 1 First call OnTouch () after calling Ontouchevent ( * 2 handles the touch event in the Ontouch () method, that is, processing a series of ACTION_DOWN,ACTION_MOVE,ACTION_UP events * returns False when the event is represented (each individual action_down,action_ MOVE,ACTION_UP is called an event, not that the three are linked together is an event) * Ontouchevent (event) is not consumed before it is called. * 3 The Action_up event in Ontouchevent will call PerformClick () to handle the onclick click event!!!! * 4 therefore: * 4.1 Touch event occurs and is processed before the Click event, and note that the Ontouch () method returns false by default. * 4.2 Only when Ontouch () returns False (that is, the event is not consumed) will call ontouchevent () * 4.3 in ontouchevent () action_up event will call PerformClick () atThe onclick click event. * 5 See the following ontouchevent () source code, please note the third if judgment, this if judgment is very important!!!!!!! * 5.1 In the IF condition, determine whether the control is clickable (clickable) or whether it can be long-pressed (long_clickable). * 5.2 If any of the conditions in clickable and long_clickable are met, always return True to Ontouchevent () method * 5.3 If clickable and long_ Clickable these two conditions are not satisfied then return false to the Ontouchevent () method * * Please NOTE: * button is clickable and long_clickable by default, but ImageView in * default condition The lower clickable and LONG_CLICKABL are not available. * * So there is a difference between using button and ImageView to experiment with Ontouchlistener and Onclicklistener respectively. * Note again: the OnTouch () method returns false by default. * 1 button do an experimental analysis dispatchtouchevent (). * Montouchlistener.ontouch () returns False (the default value), so dispatchtouchevent () * If not satisfied in the source code above, so continue to call Ontouchevent (event) because the button is full Foot clickable and long_clickable * So the last return to Dispatchtouchevent () is true, that is, the continuation event is distributed. * So you can capture a series of: Action_down,action_move,action_up. * This explains why in the button although Ontouch () returns False (the default), event distribution continues!!!!!!!!!!!!! * * 2 use ImageView to do experimental Analysis dispatchtouchevent (). * Montouchlistener.ontouch () returns False (the default value), so dispatchtouchevent () * If not satisfied in the source code above, call Ontouchevent (EVENT) The final return to Dispatchtouchevent () is false, that is, the distribution of the terminating event, because ImageView does not meet any of the clickable and long_clickable *. So for ImageView only * A Ction_down no Action_move and action_up * This explains why the event distribution is terminated in ImageView (the default value) in Ontouch () return!!!!!!!!!!!!! * * How to make ImageView like button "Normal" event distribution, there are two methods: * 1 set Setontouchlistener for ImageView, and return true in its Ontouch () method instead of the default Fals E. * 2 for ImageView set android:clickable= "true" or ImageView set Onclicklistener. * That means let ImageView be clickable. * 3 details see the example in the following code, which is reflected in the following example. * * * * Reference: * http://blog.csdn.net/guolin_blog/article/details/9097463 * Thank you very much * * Code essay: * Have seen events before The distribution, also summed up himself, can not be understood enough. * Recently planned to combine the previous stuff with Guo Da's blog to reorganize the event distribution. * As a result of the differences in understanding Guo Da the side of the blog, I see more difficult, and later also communicated with him. * So here is your own understanding, is correct, just in the expression and his blog is different.    */public class Mainactivity extends Activity {private Button Mbutton; Private ImageView Mimageview; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.main); Initbutton (); Initimageview ();} Private void Initbutton () {mbutton= (Button) Findviewbyid (R.id.button); Mbutton.setontouchlistener (new Ontouchlistener () {@ Overridepublic boolean OnTouch (View V, motionevent event) {switch (event.getaction ()) {case Motionevent.action_down: System.out.println ("button Action_down"); break;case MotionEvent.ACTION_MOVE:System.out.println ("button action_ MOVE "); break;case MotionEvent.ACTION_UP:System.out.println (" button action_up "); break;default:break;} return false;}}); Mbutton.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {System.out.println ("button Clicked ");}}); private void Initimageview () {mimageview= (ImageView) Findviewbyid (R.id.imageview); Mimageview.setontouchlistener ( New Ontouchlistener () {@Overridepublic Boolean onTouch (View V, motionevent event) {switch (event.getaction ()) {case Motio NEvent.ACTION_DOWN:System.out.println ("ImageView action_down"); Break;case Motionevent.action_move: System.out.println ("ImageView action_move"); Break;case MotionEvent.ACTION_UP:System.Out.println ("ImageView action_up"); break;default:break;}    return false;}}); Because the ImageView default is not clickable, so if you block the following code, then only//imageview Action_down not action_move and Action_ Upmimageview.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {System.out.println (" ImageView Clicked ");}});}    /* * Here is Ontouchevent Source: public boolean ontouchevent (Motionevent event) {final int viewflags = mviewflags;        if ((ViewFlags & enabled_mask) = = DISABLED) {//A DISABLED view that is clickable still consumes the touch        Events, it just doesn ' t respond to them.                Return (((viewflags & clickable) = = Clickable | |    (ViewFlags & long_clickable) = = long_clickable));        if (mtouchdelegate! = null) {if (Mtouchdelegate.ontouchevent (event)) {return true;            }} if (((viewflags & clickable) = = Clickable | | (ViewFlags & long_clickable) = = long_clickable)) {switch (event.getaction ()) {CASE MotionEvent.ACTION_UP:boolean prepressed = (mprivateflags & prepressed)! = 0; if ((Mprivateflags & PRESSED)! = 0 | | prepressed) {//Take focus if we don't have it already and W                    e should in//touch mode.                    Boolean focustaken = false; if (isfocusable () && isfocusableintouchmode () &&!isfocused ()) {Focustaken = Reque                    Stfocus ();                         if (!mhasperformedlongpress) {//This was a tap, so remove the Longpress check                        Removelongpresscallback ();                            Only perform take click Actions if we were in the pressed state if (!focustaken) { Use a Runnable and post this rather than calling//PerformClick directly. This lets other visual state//Of The view update before click Actions Start.                            if (Mperformclick = = null) {Mperformclick = new PerformClick ();                            } if (!post (Mperformclick)) {PerformClick ();                        }}} if (munsetpressedstate = = null) {                    Munsetpressedstate = new Unsetpressedstate ();                        } if (prepressed) {mprivateflags |= PRESSED;                        Refreshdrawablestate ();                    Postdelayed (Munsetpressedstate, Viewconfiguration.getpressedstateduration ());                        } else if (!post (munsetpressedstate)) {//If the post failed, unpress right now                    Munsetpressedstate.run (); } RemovEtapcallback ();            } break; Case MotionEvent.ACTION_DOWN:if (Mpendingcheckfortap = = null) {Mpendingcheckfortap = n                EW Checkfortap ();                } mprivateflags |= prepressed;                Mhasperformedlongpress = false;                Postdelayed (Mpendingcheckfortap, Viewconfiguration.gettaptimeout ());            Break                Case MotionEvent.ACTION_CANCEL:mPrivateFlags &= ~pressed;                Refreshdrawablestate ();                Removetapcallback ();            Break                case MotionEvent.ACTION_MOVE:final int x = (int) event.getx ();                Final int y = (int) event.gety ();                Be lenient about moving outside of buttons int slop = Mtouchslop; if ((x < 0-slop) | |                        (x >= getwidth () + slop) | | (Y < 0-slop) | | (Y >= getheight () + slop))          {          Outside button Removetapcallback ();                        if ((Mprivateflags & PRESSED)! = 0) {//Remove any future long Press/tap checks                        Removelongpresscallback ();                        Need to switch from pressed to not pressed mprivateflags &= ~pressed;                    Refreshdrawablestate ();        }} break;    } return true; } return false;} */



Buttonsubclass as follows:

Package Cc.cv;import Android.content.context;import Android.util.attributeset;import android.view.MotionEvent; Import Android.view.viewgroup;import Android.widget.button;public class Buttonsubclass extends Button {public Buttonsubclass (Context context) {super (context);//TODO auto-generated Constructor stub}public Buttonsubclass (context Context, AttributeSet Attrs) {Super (context, attrs);//TODO auto-generated constructor stub}public Buttonsubclass ( Context context, AttributeSet attrs, int defstyle) {Super (context, attrs, defstyle);//TODO Auto-generated constructor Stu b} @Overridepublic Boolean ontouchevent (Motionevent event) {//TODO auto-generated method Stubreturn super.ontouchevent ( event);} @Overridepublic boolean dispatchtouchevent (Motionevent event) {//TODO auto-generated method Stubreturn Super.dispatchtouchevent (event);}}

Main.xml as follows:
<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 " >    <button        android:id= "@+id/button"        android:layout_width= "wrap_content"        android:layout_ height= "Wrap_content"        android:layout_centerhorizontal= "true"        android:layout_margintop= "100dip        " android:text= "button"/>    <imageview        android:id= "@+id/imageview"        android:layout_width= "wrap _content "        android:layout_height=" wrap_content "        android:layout_centerhorizontal=" true "        Android: layout_margintop= "200dip"        android:src= "@drawable/ic_launcher"/></relativelayout>



Ps:

The event distribution was also sorted out before, but it was too superficial.

The part was recently re-organized; The end of the month is a farewell to this year.

In fact, this part of the core lies in the ViewGroup dispatchtouchevent () source part.

This arrangement, for this part is still not fully understand, look forward to have the opportunity to continue.

Learning is a process, and that is the embodiment.

Android Event distribution detailed (i)--view event distribution

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.