Take the example of a custom Testbutton.
We can handle messages such as down move up by overriding the Ontouchevent method:
?
| 123456789101112131415161718 |
public class TestButton extends Button { public TestButton(Context context) { super(context); // TODO Auto-generated constructor stub } public TestButton(Context context, AttributeSet attributeSet) { super(context, attributeSet); // TODO Auto-generated constructor stub } @Override public boolean onTouchEvent(MotionEvent event) { boolean value = super.onTouchEvent(event); System.out.println("super.onTouchEvent: " + value+ " event: " + event.getAction()); return value; } |
You can also achieve the same goal by implementing the Ontouchlistener interface, and then setting the Testbutton Ontouchlistener
?
| 1234567 |
classOnTouchListenerTest implements View.OnTouchListener{ @Override public boolean onTouch(View v, MotionEvent event) { return false; } } |
?
| 123 |
TestButton b = (TestButton)findViewById(R.id.button);OnTouchListenerTest listener = newOnTouchListenerTest();b.setOnTouchListener(listener); |
But what is the difference between these two types of monitoring?
First look at the Android source code in the view of the implementation of Dispatchtouchevent:
?
| 123456789101112131415 |
public boolean dispatchTouchEvent(MotionEvent event){ ... ... if(onFilterTouchEventForSecurity(event)){ ListenerInfo li = mListenerInfo; if(li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && li.mOnTouchListener.onTouch(this, event)) { return true; } if(onTouchEvent(event)){ return true; } } ... ... return false;} |
You can see that the priority of the Ontouchlistener interface is higher than ontouchevent, if the Ontouch method in Ontouchlistener returns True,
Said the incident has been consumed, the ontouchevent is not receiving news.
Because the button's PerformClick is implemented using Ontouchevent, if ontouchevent is not called, then the button's Click event is not responding.
In general terms:
Ontouchlistener's Ontouch method has a higher priority than ontouchevent, which is triggered first.
If the Ontouch method returns False, then the ontouchevent is triggered, and the Ontouchevent method is not called.
Built-in implementations such as the Click event are based on Ontouchevent, and if Ontouch returns True, these events will not be triggered.
Ontouchevent and Ontouch differences for Android view