In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "how to distribute and handle events in Android". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Basic reserves View, MotionEvent
We can all describe in detail the four major components of Android: Activity,Service,ContentProvider and BoardcastReceiver, but apart from the four components, we also use a lot of them, including View,View as an entry point for users to communicate with the program and a window for the program to display information to users. With regard to View, some basic attributes need to be understood. Left,top,right,bottom represents the coordinates of the upper left corner and lower right corner of view relative to the x axis and y axis, respectively, and the values of getWidth and getHeight of view are calculated from these four values. In addition, the attributes X and translationY are added to Android3.0 to facilitate our translation operation of view. X and y represent the xy coordinates of the current upper left corner of view. TranslationX and translationY represent the offset of view from its parent container, and the default value is 0.
MotionEvent means that a user's touch event, a user's click, touch or slide will produce a series of MotionEvent:
MotionEvent.ACTION_DOWN indicates that the user's fingers have just touched the screen.
MotionEvent.ACTION_MOVE indicates that the user's fingers are moving
MotionEvent.ACTION_UP means that the user's fingers are lifted from the screen.
So one time a user touches the screen may produce these events:
Click on the screen and release, Down- > Up
Click on the screen, then slide a distance, release the screen, Down- > Move- > … -> Move- > Up
With these basics in mind, let's learn how to distribute these events.
ViewGroup Distribution-> Intercept-> processing
First of all, although ViewGroup also inherits from View, but because in event interception, ViewGroup is easier to analyze and understand, so let's start with ViewGroup. The event handling of View is also briefly introduced below.
In the process of event distribution, three main methods are involved:
DispatchTouchEvent (MotionEvent event)
OnInterceptTouchEvent (MotionEvent event)
OnTouchEvent ()
At first glance, these three methods have a hoop, but if you get into the source code with your head covered at this time, you will be even more confused. Here, I will borrow a big piece of pseudo code from Ren Yugang to explain the relationship between the three:
Public boolean dispatchTouchEvent (MotionEvent event) {boolean consume = false; if (onInterceptTouchEvent (event)) {consume = onTouchEvent (event);} else {consume = child.dispatchTouchEvent (event);} return consume;}
From this pseudo code, we can see that in dispatchTouchEvent, first call ViewGroup's own onInterceptTouchEvent method to determine whether you want to intercept. If you intercept yourself at this time, call your own onTouchEvent method. If the onTouchEvent method returns True, then the event is consumed, and the event delivery ends here. If False is returned, it proves that the MotionEvent is not consumed this time, then the event will be returned upwards. Continue to be processed by the higher level If the onInterceptTouchEvent of the current ViewGroup returns False, the dispatchTouchEvent method of its child view will be called, and the event will be passed on. If its child View cannot handle it, it will come back to call the onTouchEvent method of ViewGroup. Of course, this is not reflected in this pseudo-code, which is explained by a popular example:
The leader received a task (possibly from a superior), took a look at it, and then decided to have a good rest. If he didn't work today, he handed over the task to his Xiao Wang. Xiao Wang's default attribute is to take the task as long as he comes, and to do it. If it is a simple task, Xiao Wang will solve it, and the task will be completed. Unfortunately, This time, Xiao Wang did not solve the task, and then gave feedback to the leader that the leader had no way, and no one under him could solve it, so he had no choice but to do it on his own, so he began to solve the problem, and then solved it, and the task was completed.
This is the event distribution in the ViewGroup layer. Of course, it is not that simple. It is only understood in a simple way. In fact, there are many problems that need to be paid attention to in real event distribution:
A completed sequence of events begins with Down, may contain several Move, and then ends with Up
Once a view intercepts an event, the complete event sequence of the current event will be handled by the view, which is reflected in the real code, that is, once the view intercepts the down event, then the subsequent move and up events will not call onInterceptTouchEvent, but will be handled directly by it, which means that it is not appropriate to handle events in onInterceptTouchEvent, because it is possible to skip the onInterceptTouchEvent method. This also means that once a ViewGroup does not intercept ACTION_DOWN, it will not receive any other Action in this event sequence, so you need to be especially careful when dealing with ACTION_DOWN.
In onTouchEvent, it is necessary to judge the Action of MotionEvent, because the onTouchEvent method will be called twice with one click, one is ACTION_DOWN, the other is ACTION_UP, and there will be several ACTION_MOVE if the hand slips.
ViewGroup does not intercept any events by default, and the onInterceptTouchEvent method of ViewGroup in the source code returns false by default.
The whole event distribution seems to be passed from outside to inward, and the parent View passes the event to the child View. Theoretically, the child View has no way to affect the event handling of the parent View, but there is a marker bit, the requestDisallowInterceptTouchEvent method, through which the child View can influence the event handling of the parent view. This can be used to resolve the sliding conflict between the parent view and the child view. If you want to know more, you can search for its relevant usage. It will not be unfolded here.
View can only bear it silently.
View is different from ViewGroup in that there is no onInterceptTouchEvent method in View, because as the * level of event processing, View does not need to determine whether to intercept, but must intercept, regardless of whether it can be handled or not, you have to try it, so the calling process in View is:
DispatchTouchEvent-> onTouchEvent
Moreover, the return value of * onTouchEvent is True by default, which means it is usually consumed when the event is passed. It only depends on whether it is intercepted midway. At this time, readers may wonder: is the return value of onTouchEvent of TextView also True? The answer is: yes, then why does clicking on TextView still trigger the onTouchEvent of its parent view? in theory, it should not be that TextView consumes this event and does not return. This is true in theory, but because the clickable and longClickable properties of TextView are both false, when both attributes are false, TextView will not consume events, so TextView will not consume events, which explains why putting a TextView on top of a Button and then clicking TextView can still trigger the click event of Button.
I may need to remind you here that it is a pit I stepped on before. I set the enable status of a view to false, and then added onClickListener to it. At this time, I thought that its click event would not be triggered, but it could still be clicked. Later, I learned that the enable status of view has nothing to do with onTouchEvent, only the clickable state has an impact on onTouchEvent. Setting enable of view to false does set clickable of view to false, but setting onclickListener of view turns clickable of view into true, so the solution of * is to change the order of those two lines of code, and the problem is solved.
Detailed explanation of processing GesutureDetector
After a lot of hard work, we finally intercepted the incident, and then we need to do something, otherwise we are sorry for wasting so much tongue. when it comes to handling the event, the first thing we think of is setOnClickListener, but we do not realize that the priority of onClickListener is *, and the priority will be explained in the next section, and here, we will mainly think about how to deal with the event, when we excitedly get a series of events. But we don't know how to do it, and even the simplest click events have to be dealt with by ourselves, not to mention translation, rotation and zooming, but the official GestureDetector provides us with the possibility.
Official GestureDetector is a gesture-assisted detection class that can detect a variety of gestures by default:
Class SimpleGestureListener implements GestureDetector.OnGestureListener {@ Override public boolean onDown (MotionEvent e) {return false;} @ Override public void onShowPress (MotionEvent e) {} @ Override public boolean onSingleTapUp (MotionEvent e) {return false;} @ Override public boolean onScroll (MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {return false } @ Override public void onLongPress (MotionEvent e) {} @ Override public boolean onFling (MotionEvent E1, MotionEvent e2, float velocityX, float velocityY) {return false;}}
Through this class, we can easily deal with various gestures such as sliding and double clicking besides clicking and long pressing, and deal with them separately. If these still do not satisfy your curiosity, then there is an official ScaleGestureDetector, which can be judged from the name to be an auxiliary class for detecting zoom gestures, and there are auxiliary classes for Daniel to translate and rotate following the idea of ScaleGestureDetector. Then we can almost do whatever we want according to these helper classes. Here I write a small Demo that supports translation, scaling, and rotation.
Private void init () {scaleGesture = new ScaleGestureDetector (getContext (), new ScaleListener ()); moveGesture = new MoveGestureDetector (getContext (), new MovingListener ()); rotateGesture = new RotateGestureDetector (getContext (), new RotateListener ());} @ Override public boolean onTouchEvent (MotionEvent event) {scaleGesture.onTouchEvent (event); moveGesture.onTouchEvent (event); rotateGesture.onTouchEvent (event) Return true;} private class ScaleListener implements ScaleGestureDetector.OnScaleGestureListener {@ Override public boolean onScale (ScaleGestureDetector detector) {setScaleX (detector.getScaleFactor () * getScaleX ()); setScaleY (detector.getScaleFactor () * getScaleY ()); return true } @ Override public boolean onScaleBegin (ScaleGestureDetector detector) {return true;} @ Override public void onScaleEnd (ScaleGestureDetector detector) {}}
OnTouchListener OnTouchEvent OnClickListener
We must all know onClickListener and onTouchListener before we know onTouchEvent, and they are both consumers of events. OnTouchListener takes effect in the onTouch method, and onTouch precedes onTouchEvent, that is, once onTouchListener is set and the * onTouch method returns True, then onTouchEvent will no longer be executed, and onClickListener has something to do with onTouchEvent. OnClickListener's onClick method is called in the default implementation of onTouchEvent. If onTouchEvent is overridden, onClickListener cannot accept ACTION_DOWN and ACTION_UP. Then setting onClickListener will no longer take effect, and the click or long press processing at this time can only be handled in onTouchEvent.
That's all for "how to implement event distribution and handling in Android". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.