android为手势检测提供了一个GestureDetector类,其实例代表了一个手势检测器。创建GestureDetector时需要传入一个GestureDetector.OnGestureListener实例作为一个监听器,负责对用户的手势行为提供响应。
使用android手势检测需要如下两个步骤:
创建一个GestureDetector对象,创建该对象时必须实现一个GestureDetector.OnGestureListener监听器实例
为应用程序的Activity的TouchEvent事件绑定监听器,在事件处理中指定把Activity上的TouchEvent事件交由GestureDetector处理
{
//定义手势监听器实例
GestureDetector detector;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建手势检测器
detector=new GestureDetector(this,this);
}
//将该Activity上的触碰事件交给GestureDetector处理
@Override
public boolean onTouchEvent(MotionEvent event)
{
return detector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent event)
{
Toast.makeText(this,"onDown",Toast.LENGTH_LONG).show();
return true;
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY)
{
Toast.makeText(this,"onFling", Toast.LENGTH_LONG).show();
return true;
}
@Override
public void onLongPress(MotionEvent event)
{
Toast.makeText(this,"onLongPress", Toast.LENGTH_LONG).show();
}
@Override
public boolean onScroll(MotionEvent event1, MotionEvent event2, float distanceX,float distanceY)
{
Toast.makeText(this,"onScroll",Toast.LENGTH_LONG).show();
return true;
}
@Override
public void onShowPress(MotionEvent event)
{
Toast.makeText(this,"onShowPress", Toast.LENGTH_LONG).show();
}
@Override
public boolean onSingleTapUp(MotionEvent event)
{
Toast.makeText(this,"onSingleTapUp", Toast.LENGTH_LONG).show();
return true;
}
}
网友评论