Linjiajia
2023-03-20 25b98735c5c0cbe40a07ae91a9fb2b204d9166b7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.android.app_base.widget;
 
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;
 
 
/**
 * @author Ljj
 * @date 2023.03.20. 16:25
 * @desc
 */
public class CustomScrollView extends ScrollView {
    int lastX = -1;
    int lastY = -1;
    public CustomScrollView(Context context) {
        super(context);
    }
 
    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    public CustomScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
 
 
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int x = (int) ev.getRawX();
        int y = (int) ev.getRawY();
        int dealtX = 0;
        int dealtY = 0;
 
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                dealtX = 0;
                dealtY = 0;
                // 保证子View能够接收到Action_move事件
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_MOVE:
                dealtX += Math.abs(x - lastX);
                dealtY += Math.abs(y - lastY);
                // 这里是够拦截的判断依据是左右滑动,读者可根据自己的逻辑进行是否拦截
                if (dealtX < dealtY) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    System.out.println("上下滑动"+true);
                    return super.dispatchTouchEvent(ev);
                } else {
                    getParent().requestDisallowInterceptTouchEvent(false);
                    System.out.println("左右滑动"+false);
                }
                lastX = x;
                lastY = y;
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            case MotionEvent.ACTION_UP:
                break;
 
        }
        return super.dispatchTouchEvent(ev);
    }
}