How to vary between child and parent view group touch events

后端 未结 2 723
眼角桃花
眼角桃花 2020-12-06 10:11

I decided to post this question and answer in response to this comment to this question:
How to handle click in the child Views, and touch in the parent ViewGroups?

2条回答
  •  抹茶落季
    2020-12-06 10:33

    Lets revamp the issue.

    You happen to have a ViewGroup with a bunch of children. You want to intercept the touch event for everything withing this ViewGroup with a minor exception of some children.

    I have been looking for an answer for the same question for quite a while. Did not manage to find anything reasonable and thus came up on my own with the following solution.

    The following code snippet provides an overview of the ViewGroup's relevant code that intercepts all touches with the exception of the ones coming from views that happen to have a special tag set (You should set it elsewhere in your code).

    private static int NO_INTERCEPTION;
    
    private boolean isWithinBounds(View view, MotionEvent ev) {
        int xPoint = Math.round(ev.getRawX());
        int yPoint = Math.round(ev.getRawY());
        int[] l = new int[2];
        view.getLocationOnScreen(l);
        int x = l[0];
        int y = l[1];
        int w = view.getWidth();
        int h = view.getHeight();
        return !(xPoint < x || xPoint > x + w || yPoint < y || yPoint > y + h);
    }
    
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        for (int i=0; i

提交回复
热议问题