手指划动切换Activity
以下代码用于Activity之间的划动切换,大概实现原理就是判断手指的划动速度和划动方向以确定向哪个Activity跳转,switchTo***Activity()为Activity的跳转方法
private VelocityTracker velocityTracker;//用于得到手势在屏幕上的滑动速度 private static final int VELOCITY = 600; @Override public boolean onTouchEvent(MotionEvent event) { String localClassName = getLocalClassName();//当前所在类名 LogUtil.log(TAG, "class Name:"+localClassName); int action = event.getAction(); //float x = event.getX(); //float y = event.getY(); switch (action) { case MotionEvent.ACTION_DOWN: if(velocityTracker == null){ velocityTracker = VelocityTracker.obtain();//取得手势在屏幕上的滑动速度 velocityTracker.addMovement(event); } //lastMotionX = x; break; case MotionEvent.ACTION_MOVE: //int deltaX = (int) (lastMotionX - x); if(velocityTracker != null){ velocityTracker.addMovement(event); } //lastMotionX = x; break; case MotionEvent.ACTION_UP: int velocityX = 0; if(velocityTracker != null){ velocityTracker.addMovement(event); velocityTracker.computeCurrentVelocity(1000);//计算每秒滑动多少个像素 velocityX = (int) velocityTracker.getXVelocity();//最后计算检索X速度 } if(velocityX > VELOCITY ){ if("ui.MainActivity".equals(localClassName)){ switchToTvLiveActivity(); }else if("ui.LocalMediaActivity".equals(localClassName)){ switchToMainActivity(); }else if("ui.NetMediaActivity".equals(localClassName)){ switchToLocalMediaActivity(); }else if("ui.TvLiveActivity".equals(localClassName)){ switchToNetMediaActivity(); } } else if(velocityX < -VELOCITY ){ if("ui.MainActivity".equals(localClassName)){ switchToLocalMediaActivity(); }else if("ui.LocalMediaActivity".equals(localClassName)){ switchToNetMediaActivity(); }else if("ui.NetMediaActivity".equals(localClassName)){ switchToTvLiveActivity(); }else if("ui.TvLiveActivity".equals(localClassName)){ switchToMainActivity(); } } if(velocityTracker != null){ velocityTracker.recycle();//回收 velocityTracker = null; } break; } return true; }