16

What is the difference between a view's onTouchEvent :

public class MyCustomView extends View {
    // THIS :
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }
}

and its onTouchListener :

MyCustomView myView = (MyCustomView) findViewById(R.id.customview);
myView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public void onClick(View arg0) {
        // do something
    }
});

or

public class MyCustomView extends View {

    public MyCustomView(Context context, AttributeSet attrs) {
        // THIS :
        setOnTouchListener(new View.OnTouchListener() {
            @Override
            public void onClick(View arg0) {
                // do something
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }
}

If this two is different,
Do we need to implement both ?
Which one is invoked first ?

If I have some scrolling and zooming functionality, should I implement them inside onTouchEvent or onTouchListener ?

topher
  • 1,357
  • 4
  • 17
  • 36

2 Answers2

14

Answer by LeeYiHong is correct, and the other very important thing is what is written at http://developer.android.com/reference/android/view/View.OnTouchListener.html:

The callback [i.e. View.OnTouchListener -> onTouch(View v, MotionEvent event)] will be invoked before the touch event [i.e. onTouchEvent(MotionEvent)] is given to the view.

Elia12345
  • 326
  • 3
  • 5
  • 6
    Other than where they "work" and the order they're processed, is there any functional difference between them? In other words, is there anything you can do with one that you cannot do with the other? or more easily? Why would someone choose one over the other, or is it a complete toss-up? – gotube Apr 05 '15 at 21:58
3

I am not sure if you had found your answer. But I found related questions similar to yours.

"onTouch works everywhere you want (whether it is in activity or view) as long as you have declared the interface and put the Listener right! On the other hand, onTouchEvent only works inside a View!"

For scrolling and zooming functionality, I guess onTouchListener will be enough to complete both function (and many more like rotation etc).

Community
  • 1
  • 1
Lee Yi Hong
  • 1,310
  • 13
  • 17
  • 2
    What do you mean by "works"? What does it mean to say onTouchEvent doesn't work inside an Activity? Do you mean you can only implement onTouchEvent in a View object? – gotube Apr 05 '15 at 21:57