要实现左右滑动的效果,就一定要有手势识别器,就是这个对象 GestureDetector。
步骤:
1.初始化手势识别器
2.注册手势识别的touch事件
import android.os.Bundle; import android.view.GestureDetector; import android.view.MotionEvent; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; public abstract class BaseActivity extends AppCompatActivity { private GestureDetector mGestureDetector; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 1.初始化手势识别器 mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // e1:第一次按下的位置 e2:当手离开屏幕时的位置 velocityX:沿x轴的速度 velocityY:沿Y轴方向的速度 // 判断e1和e2是否为空 if (e1 == null || e2 == null) { return false; } // 判断竖直方向移动的大小 if (Math.abs(e1.getRawY() - e2.getRawY()) > 100) { // Toast.makeText(getApplicationContext(), "动作不合法", 0).show(); return true; } // 判断水平方向移动的速度 if (Math.abs(velocityX) < 150) { // Toast.makeText(getApplicationContext(), "移动的太慢", 0).show(); return true; } if ((e1.getRawX() - e2.getRawX()) > 200) {// 向左滑动 moveLeft(); return true; } if ((e2.getRawX() - e1.getRawX()) > 200) {// 向右滑动 moveRight(); return true;// 消费掉当前事件,不让当前事件继续向下传递 } return super.onFling(e1, e2, velocityX, velocityY); } }); } /** * 向右滑动 */ protected void moveRight() { } /** * 向左滑动 */ protected void moveLeft() { } // 重写activity的触摸事件 @Override public boolean onTouchEvent(MotionEvent event) { // 2.让手势识别器生效 if (useGestureDetector()) { mGestureDetector.onTouchEvent(event); } return super.onTouchEvent(event); } /** * 使用手势识别器 * * @return */ protected boolean useGestureDetector() { return true; } }