任何图形部件都可以处理触摸事件。通常情况下使用 View 或 Activity。
有几种处理触摸的方法,但我建议GestureListener:
public class GestureListener implements GestureDetector.OnGestureListener
{
MyView appliedView; //view who responses to graphical gestures
public GestureListener(MyView currentView)
{
this.appliedView = currentView;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float dx,
float dy) {
//make your view response to gestures
appliedView.onGestureMove(e1, e2, dx, dy);
return true;
}
@Override
public boolean onDown(MotionEvent arg0) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX,
float velocityY) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
}
在你的 View 类中:
public class MyView extends View
{
private GestureDetector gestureMgr;
public MyView(Context context)
{
super(context);
gestureMgr= new GestureDetector(context, new GestureListener(this));
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
return gestureMgr.onTouchEvent(event);
}
public void onGestureMove(MotionEvent e1, MotionEvent e2, float dx, float dy)
{
//check obj is touched or not
//do moving objects around
}
}