1. 效果图,本功能用了ViewFlipper和GestureDetector (手势检测器)两个关键技术点:
2. 先写好布局文件,这里用到了ViewFlipper类,用于切换视图,毕竟ViewFlipper见得少,先介绍一下。
在xml布局中的方法介绍:
android:autoStart: 设置自动加载下一个View
android:flipInterval:设置View之间切换的时间间隔
android:inAnimation: 设置切换View的进入动画
android:outAnimation:设置切换View的退出动画
当然同样的在代码中也可以设置:
isFlipping: 判断View切换是否正在进行
setFilpInterval:设置View之间切换的时间间隔
startFlipping: 开始View的切换,而且会循环进行
stopFlipping: 停止View的切换
setOutAnimation:设置切换View的退出动画
setInAnimation: 设置切换View的进入动画
showNext: 显示ViewFlipper里的下一个View
showPrevious: 显示ViewFlipper里的上一个View
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andro xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".slide.Main2Activity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="start" android:text="开始自动翻页" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:onClick="stop" android:text="停止自动翻页" /> </LinearLayout> <ViewFlipper android: android:layout_width="match_parent" android:layout_height="match_parent" android:flipInterval="1500"></ViewFlipper> //flipInterval 实现自动翻转时添加,值为每页翻转的时间 </LinearLayout>
3. 接下来是代码部分,首页介绍一下GestureDetector :
GestureDetector.OnGestureListener里包含的事件处理方法如下:
➢boolean onDown(MotionEvent e):当触碰事件按下时触发该方法。
➢boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY):当用户手指在触摸屏_上“拖过”时触发该方法。其中velocityX、velocityY 代表“拖过”动作在横向、纵向,上的速度。
➢abstract void onL ongPress(MotionEvente):当用户手指在屏幕上长按时触发该方法。
➢boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY):当用户手指在屏幕上“滚动”时触发该方法。
➢void onShowPress(MotionEvent e):当用户手指在触摸屏上按下,而且还未移动和松开时触发该方法。
➢boolean onSingleTapUp(MotionEvent e): 用户手指在触摸屏上的轻击事件将会触发该方法。
*使用Android的手势检测只需两个步骤。
➊创建一个GestureDetector 对象。创建该对象时必须实现一个GestureDetector.OnGestureListener监听器实例。
❷为应用程序的Activity (偶尔也可为特定组件)的TouchEvent事件绑定监听器(对应gestureDetector = new GestureDetector(this, this);),在事件处理中指定把Activity (或特定组件),上的TouchEvent事件交给GestureDetector处理。(对应return gestureDetector.onTouchEvent(event);)*