racumin
racumin

Reputation: 69

Why return true onSurfaceView onTouchEvent()?

I'm overriding the onTouchEvent() for my SurfaceView. Whenever I touch my phone screen, it should print the coordinates of the touch events. This is my code:

    public class MyGestureActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate()");

        panel = new MyGesturePanel(this);
        setContentView(panel);
        }
    }

    public class MyGesturePanel extends SurfaceView implements SurfaceHolder.Callback {
    public boolean onTouchEvent(MotionEvent event) {
        Log.i(TAG, "onTouchEvent! " + event.getX() + " " + event.getY());
        return super.onTouchEvent(event);
    }
    }

If I returned super.onTouchEvent(event), it only prints 1 event (ACTION_DOWN) even if I did not release my finger on the screen. I also tried to print what was returned and it returned false.

Now, instead of using super.onTouchEvent(event), I returned true. When I set the return value to true, it functions normally. When I held my finger on the screen, it prints lots and lots of ACTION_MOVE events. (even though I'm not moving my finger)

Why is that? Am I doing something wrong? Is it advisable to just "hardcode" the return to true?

Thanks!

Upvotes: 1

Views: 1886

Answers (1)

Mohamed_AbdAllah
Mohamed_AbdAllah

Reputation: 5322

Returning true in an onTouchEvent() tells Android system that you already handled the touch event and no further handling is required. If you return false, Android system will be the handler of the onTouch event and will override your code for any events past ACTION_DOWN (which is the first event when you touch the screen).

Upvotes: 3

Related Questions