在Android中我们实现页面翻页或图片切换,通常会用到ViewPager,但是如果想要实现Activity翻页,则ViewPager是无法实现的,因此本案例中实现上下左右滑动并页面切换,用到的是由OnTouchListener监听事件结合GestureDetector,SimpleOnGestureListener手势监听事件来实现的左右滑动示例。
我们都知道ViewPager只能用来翻页fragment或者图片之类的控件,如果想要实现滑动Activity翻页,则无法实现,因此本示例将以Activity滑动翻页为例,封装成OnSwipeTouchListener监听类来实现。
OnSwipeTouchListener代码:
package com.example.animationdemo; import android.content.Context; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; public class OnSwipeTouchListener implements View.OnTouchListener { private final GestureDetector gestureDetector; private Context context; public boolean onTouch(final View view, final MotionEvent motionEvent) { return gestureDetector.onTouchEvent(motionEvent); } public GestureDetector getGestureDetector(){ return gestureDetector; } public OnSwipeTouchListener(Context context) { super(); this.context = context; gestureDetector = new GestureDetector(context, new GestureListener()); } private final class GestureListener extends GestureDetector.SimpleOnGestureListener { //滑动距离 private static final int SWIPE_THRESHOLD = 100; //手势速度 private static final int SWIPE_VELOCITY_THRESHOLD = 100; @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { boolean result = false; try { float diffY = e2.getRawY() - e1.getRawY(); float diffX = e2.getRawX() - e1.getRawX(); if ((Math.abs(diffX) - Math.abs(diffY)) > SWIPE_THRESHOLD) { if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (diffX > 0) { onSwipeRight(); } else { onSwipeLeft(); } } } else { if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) { if (diffY > 0) { onSwipeBottom(); } else { onSwipeTop(); } } } } catch (Exception e) { } return result; } } /** * On swipe right. */ public void onSwipeRight() { } /** * On swipe left. */ public void onSwipeLeft() { } /** * On swipe top. */ public void onSwipeTop() { } /** * On swipe bottom. */ public void onSwipeBottom() { } }
然后在OneActivity中添加方法,滑动跳转到TwoActivity中,例如OneActivity.xml所有控件都是由ConstraintLayout包裹的,那么我们可以在OneActivity中的onCreate中添加如下代码,实现Activity滑动切换页面:
constraint_layout = findViewById(R.id.constraint_layout); constraint_layout.setOnTouchListener(new OnSwipeTouchListener(this){ @Override public void onSwipeLeft() { super.onSwipeLeft(); //Activity滑动翻页 startActivity(new Intent(OneActivity.this,TwoActivity.class)); } @Override public void onSwipeRight() { super.onSwipeRight(); } @Override public void onSwipeTop() { super.onSwipeTop(); } @Override public void onSwipeBottom() { super.onSwipeBottom(); } });
Android实现界面左右滑动切换翻页,这个OnSwipeTouchListener工具类能够很好的帮助您实现翻页功能,而不需要用到麻烦的ViewPager,甚至ViewPager根本无法实现Activity的滑动翻页效果。