Android: How to prevent any touch events from being passed from a view to the one underneath it?

前端 未结 8 713
深忆病人
深忆病人 2021-01-31 13:38

Specifically using the code below, is there a way to modify it so that the activity under this newly created view does not receive any gestures?

View v1 = new Vi         


        
相关标签:
8条回答
  • 2021-01-31 14:16

    I'm a little late to the party but I don't think the accepted solution is very great. Here is a static method that accepts any number of views and disables this event bubbling. This has worked for me 100% of the time for API 17+ (lower untested)

    public static void disableEventBubbling(View... views){
        for(View view : views){
            if(view != null){
                view.setOnTouchListener(new View.OnTouchListener(){
                   @Override
                    public boolean onTouch(View view, MotionEvent event){
                        view.getParent().requestDisallowInterceptTouchEvent(true);
                        return false;
                    }
                });
            }
        }
    }
    

    You can add a case for whatever kind of event you want, or you could get rid of the switch and make the default case the only line inside the touch listener.

    0 讨论(0)
  • 2021-01-31 14:18

    all you need to do is just call

    arg0.getParent().requestDisallowInterceptTouchEvent(true);
    

    at the beginning of your onTouch function. Like thsi -

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            arg0.getParent().requestDisallowInterceptTouchEvent(true);
            switch(arg1.getActio){
            }
    
            return false; 
    
         }
    
    0 讨论(0)
提交回复
热议问题