内容字号:默认大号超大号

段落设置:段首缩进取消段首缩进

字体设置:切换到微软雅黑切换到宋体

Android手势识别简单封装类

2016-07-21 15:20 出处:电脑高手网整理 人气: 评论(0

   在做一个项目时用到了简单的手势功能(向左,向右滑切屏),于是简单地封装了下

  import android.content.Context;

  import android.util.DisplayMetrics;

  import android.view.GestureDetector;

  import android.view.GestureDetector.OnGestureListener;

  import android.view.MotionEvent;

  public class GestureHelper implements OnGestureListener {

  private GestureDetector gesture_detector;

  private int screen_width;

  private OnFlingListener listener_onfling;

  public static abstract class OnFlingListener {

  public abstract void OnFlingLeft();

  public abstract void OnFlingRight();

  }

  public GestureHelper(Context context) {

  DisplayMetrics dm = context.getResources().getDisplayMetrics();

  screen_width = dm.widthPixels;

  gesture_detector = new GestureDetector(context, this);

  }

  public void setOnFlingListener(OnFlingListener listener) {

  listener_onfling = listener;

  }

  public boolean onTouchEvent(MotionEvent event) {

  return gesture_detector.onTouchEvent(event);

  }

  @Override

  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

  // 触发条件 :

  // X轴的坐标位移大于FLING_MIN_DISTANCE,且移动速度大于FLING_MIN_VELOCITY个像素/秒

  final int FLING_MIN_DISTANCE = (int) (screen_width / 3.0f), FLING_MIN_VELOCITY = 200;

  if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {

  listener_onfling.OnFlingLeft();

  } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {

  listener_onfling.OnFlingRight();

  }

  return true;

  }

  @Override

  public boolean onDown(MotionEvent e) {

  return false;

  }

  @Override

  public void onLongPress(MotionEvent e) {

  }

  @Override

  public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,

  float distanceY) {

  return false;

  }

  @Override

  public void onShowPress(MotionEvent e) {

  }

  @Override

  public boolean onSingleTapUp(MotionEvent e) {

  return false;

  }

  }

  使用方法如下:

  public class TestActivity extends Activity {

  private GestureHelper gh;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_start);

  gh = new GestureHelper(this);

  gh.setOnFlingListener(new OnFlingListener() {

  @Override

  public void OnFlingLeft() {

  //向左滑动

  }

  @Override

  public void OnFlingRight() {

  //向右滑动

  }

  });

  }

  @Override

  public boolean onTouchEvent(MotionEvent event) {

  return gh.onTouchEvent(event);

  }

  }

相关栏目

相关文章



分享给小伙伴们:

评论

发表评论愿您的每句评论,都能给大家的生活添色彩,带来共鸣,带来思索,带来快乐。

签名: 验证码: 点击我更换图片

评论列表

    Copyright © 2002-2016 dngsw.cn 电脑高手网 版权所有

    粤ICP备13005586号-3