import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import androidx.core.view.GestureDetectorCompat;
import androidx.core.widget.NestedScrollView;
public class CustomNestedScrollView extends NestedScrollView {
private GestureDetectorCompat gestureDetector;
private OnSwipeListener onSwipeListener;
public CustomNestedScrollView(Context context) {
super(context);
setupGestureDetector(context);
}
public CustomNestedScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
setupGestureDetector(context);
}
public CustomNestedScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setupGestureDetector(context);
}
// 设置手势识别器
private void setupGestureDetector(Context context) {
gestureDetector = new GestureDetectorCompat(context, new MyGestureListener());
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
// 将触摸事件传递给手势识别器处理
boolean result = gestureDetector.onTouchEvent(ev);
// 触摸事件未被消费时,由父类处理
if (!result) {
return super.onTouchEvent(ev);
}
return result;
}
public void setOnSwipeListener(OnSwipeListener listener) {
this.onSwipeListener = listener;
}
// 定义滑动监听器接口
public interface OnSwipeListener {
void onSwipeLeft();
void onSwipeRight();
}
// 定义手势识别监听器
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
//滑动阔值距离
private static final int SWIPE_THRESHOLD = 200;
//滑动阔值速度
private static final int SWIPE_VELOCITY_THRESHOLD = 160;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffX = e2.getX() - e1.getX();
float diffY = e2.getY() - e1.getY();
// 检测水平滑动的距离是否大于竖直滑动的距离
if (Math.abs(diffX) > Math.abs(diffY)) {
// 检测滑动距离和速度是否大于阈值
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
// 向右滑动
if (onSwipeListener != null) {
onSwipeListener.onSwipeRight();
}
} else {
// 向左滑动
if (onSwipeListener != null) {
onSwipeListener.onSwipeLeft();
}
}
result = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
}
在布局文件中使用CustomNestedScrollView代替NestedScrollView:
<com.example.app.CustomNestedScrollView
android:id="@+id/custom_nested_scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 这里放置你的 NestedScrollView 的内容 -->
</com.example.app.CustomNestedScrollView>
然后通过调用setOnSwipeListener方法来设置向左和向右滑动的监听器。
CustomNestedScrollView customNestedScrollView = findViewById(R.id.custom_nested_scroll_view);
customNestedScrollView.setOnSwipeListener(new CustomNestedScrollView.OnSwipeListener() {
@Override
public void onSwipeLeft() {
// 执行向左滑动操作
}
@Override
public void onSwipeRight() {
// 执行向右滑动操作
}
});