OnTouch and OnClick conflict handling in Android

Source: Internet
Author: User
Tags gety

In Android, when an OnTouch event and OnClick event are called for A View at the same time, the event conflicts. For example, The onClick event intends to execute action A and the OnTouch event.
It is intended to execute action B, but in actual use, it will be found that when OnTouch is called, it is possible to execute action A and action B at the same time, because the OnClick event itself is in
In the OnTouch event;
In the onTouch event, if true is returned, onClick is not executed. If false is returned, The onClick method is executed at the same time.
Points: Here I think of a method that is not perfect but completely correct, that is, when MotionEvent. ACTION_DOWN in OnTouch, record the following points (X1, Y1 ),
When MotionEvent. ACTION_UP, record the vertex (X2, Y2) and compare the distance between the two points. If it is smaller than a small value (for example, 5), it is considered a Click event.
In onTouch, false is returned. If the distance is large, it can be processed as an onTouch event and true is returned:
The example is as follows:
Public boolean onTouch (View v, MotionEvent event ){
If (event. getAction () = MotionEvent. ACTION_DOWN ){
X1 = event. getX ();
Y1 = event. getY ();
}
If (event. getAction () = MotionEvent. ACTION_UP ){
X2 = event. getX ();
Y2 = event. getY ();
If (Math. abs (x1-x2) <6 ){
Return false; // if the distance is small, it is processed as a click event.
}
If (Math. abs (x1-x2)> 60) {// real onTouch event
}
}
Return true; // return true without executing the click Event
}

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.