标签:
一、概念
手势:其实是指用户手指或触摸笔在屏幕上的连续触碰行为,Andoird对两种手势行为都提供了支持:
Andorid提供了手势检测,并为手势检测提供了相应的监听器;
Android允许开发者添加手势,并提供了相应的API识别用户手势;
二、手势检测
Gesture类:代表了一个手势检测器;
GestureDectector.OnGestureListener类:代表一个监听器、负责对用户的手势行为提供响应;
boolean onDown(MotionEvent e):当触碰事件按下时触发的方法;
boolean onFling(MotionEvent e1,MotionEvent e2,float velocityX,float velocityY):当用户在触摸屏上”拖过”时触发该方法,velocityX,velocityY代表“拖过”动作的横向、纵向上的速度;
abstract void onLongPress(MotionEvent e):当用户在屏幕上长按时触发该方法;
abstract void onScroll(MotionEvent e1,MotionEvent e2,float distanceX,float diastanceY):当用户在屏幕上“滚动”时触发该方法;
void onShowPress(MotionEvent e):当用户在屏幕上按下,而且还未移动和松动的时候触发该方法;
boolean onSingleTapUp(MotionEvent e):当用户在触摸屏上的轻击事件将会触发该方法;
三、使用步骤
创建一个GestureDetector对象,创建对象时候必须创建一个GestureDectector.OnGestureListener监听器实例;
为应用程序的Activity(偶尔也可以为特定组件)的TouchEvent事件绑定监听器,在事件处理中制定把Activity(或特定组件)上的TouchEvent事件交给GestureDetector处理;
使用实例
public class MainActivity extends Activity implements OnGestureListener { // 定义手势检测实例 GestureDetector detector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); // 创建手势检测器 detector = new GestureDetector(this, this); } @Override public boolean onTouchEvent(MotionEvent event) { // 将该Activity上的触碰事件交给GestureDetector处理 return detector.onTouchEvent(event); } @Override public boolean onDown(MotionEvent e) { // 触碰时间按下时触发该方法 Toast.makeText(this, "OnDown", Toast.LENGTH_LONG).show(); return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // 当用户在屏幕上“拖动”时触发该方法 Toast.makeText(this, "onFling", Toast.LENGTH_LONG).show(); return false; } @Override public void onLongPress(MotionEvent e) { // 当用户在屏幕上长按时触发该方法 Toast.makeText(this, "onLongPress", Toast.LENGTH_LONG).show(); } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // 当屏幕“滚动”时触发该方法 Toast.makeText(this, "onScroll", Toast.LENGTH_LONG).show(); return false; } @Override public void onShowPress(MotionEvent e) { // 当用户在触摸屏幕上按下、而且还未移动和松开时触发该方法 Toast.makeText(this, "onShowPress", Toast.LENGTH_LONG).show(); } @Override public boolean onSingleTapUp(MotionEvent e) { // 在屏幕上的轻击事件将会触发该方法 Toast.makeText(this, "onSingleTapUp", Toast.LENGTH_LONG).show(); return false; } }
标签:
原文地址:http://www.cnblogs.com/guojing1991/p/4505895.html