Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What actually happens if I return false in a OnTouchListener?

I am creating a game that requires a SurfaceView to implement OnTouchListener. During the game I want to pause the Listener for some specific time.I tried returning false from the onTouch() method , but still the method keeps executing.Is there any other way to have the listener paused for sometime? And anyone please explain what returning false from onTouch() actually mean?

like image 601
abtdw Avatar asked Feb 05 '14 13:02

abtdw


People also ask

What will happen if your Ontouch () callback returns false instead of true?

If you return false than the touch event will be passed to the next View further up in the view hierarchy and you will receive no follow up calls.

What does it mean to return false?

return false inside a callback prevents the default behaviour. For example, in a submit event, it doesn't submit the form. return false also stops bubbling, so the parents of the element won't know the event occurred.

Which of the event handlers does always need to return a Boolean return value?

In android, most event listener methods return a boolean value.

What is onTouchEvent?

onTouchEvent is a method implemented by the View, Activity and other base classes like LinearLayout, etc.. public boolean onTouchEvent(MotionEvent event) { throw new RuntimeException("Stub!" ); } you can override this method by any derived classes. whereas.


2 Answers

From the View documentation:

Returns
True if the listener has consumed the event, false otherwise.

If you return true you tell android that the press is taken care of. Forget it.

If you return false you basically say "Not my problem, Someone else will have to take care of this click". Then android will pass the event down to other views, which could be under your view.

like image 175
MartinHaTh Avatar answered Sep 30 '22 06:09

MartinHaTh


If you return true you signal the system that you have consumed the event as seen in the documentation. This means that other views that also have a touchlistener will not get this event for handling. If you return false the event will be passed to parent views for handling.

For example if you have a ListView nested inside a Viewpager the Listview is the first view that can handle the touchevent. If it is a horizontal swipe the event will not be handled through the listview and the viewpager will be able to handle the swipe.

like image 42
Janusz Avatar answered Sep 30 '22 04:09

Janusz