您的位置:首页 > 移动开发 > Android开发

android学习笔记(四)

2011-05-04 21:19 141 查看
手势识别的问题。

为了可以识别用户的手势,可以使用gesturedetector类,以motionevent对象为参数,通过ontouchevent方法,分析手势并作出反应。文

档中提到,该类仅能够处理由touch提供的motionevent,不能处理trackball的event。

为了使用该类,需要构造对象,参数为一个实现了ongesturelistener接口的对象。举例如下:

public class MyGesture extends Activity implements OnTouchListener, OnGestureListener {
private GestureDetector mGestureDetector;
public MyGesture() {
mGestureDetector = new GestureDetector(this);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.tv);
tv.setOnTouchListener(this);
tv.setFocusable(true);
tv.setClickable(true);
tv.setLongClickable(true);
mGestureDetector.setIsLongpressEnabled(true);
}

/*
* 在onTouch()方法中,我们调用GestureDetector的onTouchEvent()方法,将捕捉到的MotionEvent交给GestureDetector
* 来分析是否有合适的callback函数来处理用户的手势
*/
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
// 用户轻触触摸屏,由1个MotionEvent ACTION_DOWN触发
public boolean onDown(MotionEvent arg0) {
Log.i("MyGesture", "onDown");
Toast.makeText(this, "onDown", Toast.LENGTH_SHORT).show();
return true;
}

/*
* 用户轻触触摸屏,尚未松开或拖动,由一个1个MotionEvent ACTION_DOWN触发
* 注意和onDown()的区别,强调的是没有松开或者拖动的状态
*/
public void onShowPress(MotionEvent e) {
Log.i("MyGesture", "onShowPress");
Toast.makeText(this, "onShowPress", Toast.LENGTH_SHORT).show();
}

// 用户(轻触触摸屏后)松开,由一个1个MotionEvent ACTION_UP触发
public boolean onSingleTapUp(MotionEvent e) {
Log.i("MyGesture", "onSingleTapUp");
Toast.makeText(this, "onSingleTapUp", Toast.LENGTH_SHORT).show();
return true;
}

// 用户按下触摸屏、快速移动后松开,由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE, 1个ACTION_UP触发
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
Log.i("MyGesture", "onFling");
Toast.makeText(this, "onFling", Toast.LENGTH_LONG).show();
return true;
}

// 用户按下触摸屏,并拖动,由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE触发
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
Log.i("MyGesture", "onScroll");
Toast.makeText(this, "onScroll", Toast.LENGTH_LONG).show();
return true;
}

// 用户长按触摸屏,由多个MotionEvent ACTION_DOWN触发
public void onLongPress(MotionEvent e) {
Log.i("MyGesture", "onLongPress");
Toast.makeText(this, "onLongPress", Toast.LENGTH_LONG).show();
}
}


测试onfling时发现,view对象需要将onclickable设为true
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: