【Android】滑动屏幕效果GestureDetector、OnGestureListener、ViewFlipper

屏幕切换指的是在同一个Activity内屏幕见的切换。

通过GestureDetector、OnGestureListener实现滑屏事件。ViewFlipper是继承至FrameLayout的,所以它是一个Layout里面可以放置多个View。示例中第一页仅放了一个按钮BUTTON,向下滑屏时,每页都只放了一个TEXTVIEW。

页面:

 

Activity代码:

 

这里实现的功能是从右往左滑动则切换到上一个View,从左往右滑动则切换到下一个View,并且使用不同的in、out 动画使切换效果看起来统一一些。

滑屏实现:

通过android.view.GestureDetector类可以检测各种手势事件,该类有两个回调接口分别用来通知具体的事件:
 
GestureDetector.OnDoubleTapListener:用来通知DoubleTap事件,类似于鼠标的双击事件,该接口有如下三个回调函数:
 
1.   onDoubleTap(MotionEvent e):通知DoubleTap手势,
2.   onDoubleTapEvent(MotionEvent e):通知DoubleTap手势中的事件,包含down、up和move事件(这里指的是在双击之间发生的事件,例如在同一个地方双击会产生DoubleTap手势,而在DoubleTap手势里面还会发生down和up事件,这两个事件由该函数通知);
3.   onSingleTapConfirmed(MotionEvent e):用来判定该次点击是SingleTap而不是DoubleTap,如果连续点击两次就是DoubleTap手势,如果只点击一次,系统等待一段时间后没有收到第二次点击则判定该次点击为SingleTap而不是DoubleTap,然后触发SingleTapConfirmed事件。
GestureDetector.OnGestureListener:用来通知普通的手势事件,该接口有如下六个回调函数:
1.   onDown(MotionEvent e):down事件;
2.   onSingleTapUp(MotionEvent e):一次点击up事件;
3.   onShowPress(MotionEvent e):down事件发生而move或则up还没发生前触发该事件;
4.   onLongPress(MotionEvent e):长按事件;
5.   onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY):滑动手势事件;
6.   onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY):在屏幕上拖动事件。
本次仅用到了 OnGestureListener类中的onFling方法。  其他手势事件各位可以自己回去试验。
简单说明:
要实现屏幕切换的话,首先需要定义一个GestureDetector:
private GestureDetector mGestureDetector;
 
并在onCreate函数中初始化:
mGestureDetector =  new GestureDetector( this);
 
同时Activity要继承OnGestureListener接口,并实现其中的onFling方法。
另外Activity的onTouchEvent事件也要实现!!
另外本例View切换时还有动画效果。使用Animation类实现,相关的函数: 
  • setInAnimation:设置View进入屏幕时候使用的动画,该函数有两个版本:
一个接受单个参数,类型为android.view.animation.Animation;
一个接受两个参数,类型为Context和int,分别为Context对象和定义Animation的resourceID。
  • setOutAnimation: 设置View退出屏幕时候使用的动画,参数setInAnimation函数一样。
  • showNext: 调用该函数来显示FrameLayout里面的下一个View。
  • showPrevious: 调用该函数来显示FrameLayout里面的上一个View。

动画源文件: (在res目录下,创建一个anim文件夹,把下面的文件都放在这里)

push_left_in.xml

 

push_left_out.xml:

 

push_right_in.xml:

 

push_right_out.xml:

 

好了,就写这么多。

你可能感兴趣的:(gesturedetector)