onTouchevent() vs onTouch()

2019-01-13 03:55发布

After many experiments with onTouchEvent and onTouch, I found that 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! Is my assumption correct? Is this the real difference?

7条回答
姐就是有狂的资本
2楼-- · 2019-01-13 04:54

I had some confusion related to how onTouchEvent() and onTouch() work (You can see my comment to this question). After some research below is what I have found on it. This may be helpful to beginners.

1) Implementation:

If you want use onTouch() you have to do three things.

1- implement OnTouchListener

2- call setOnTouchListener() on the view you want to set catch the event

3- override onTouch() to handle the event

but if you want to use onTouchEvent() you don't need to do step 1 & 2 above. just you need to override onTouchEvent().

2) Working:

onTouch() works on view, viewgroup, activity. Meaning you can use onTouch() inside view, viewgroup or activity. This methods take two arguments [onTouch(View v, MotionEvent e) ]. This allows you filter events for different views in an activity or view group. Or the activity can itself handle it. onTouchEvent() takes on one argument [onTouchEvent(MotionEvent e) ]. Thus this can be used only inside the view that implements it or on the derived view. A derived View enables extension of the touch behavior defined in onTouchEvent().

I think, such options are part of Android's more flexible development philosophy, though it creates confusion for the learners at times.

查看更多
登录 后发表回答