dispatchTouchEvent in Fragment in Android

后端 未结 3 1047
深忆病人
深忆病人 2021-01-17 11:49

I am trying to get swipe up and swipe down gestures working in Fragment. The same is working fine with activity. In Fragment, I have an issue with dispatchTouchEvent. How d

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 12:01

    You must dispatchTouchEvent in your parent activity like that Add this code to parent activity:

    private List onTouchListeners;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(onTouchListeners==null)
        {
            onTouchListeners=new ArrayList<>();
        }
    }
    public void registerMyOnTouchListener(MyOnTouchListener listener){
        onTouchListeners.add(listener);
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        for(MyOnTouchListener listener:onTouchListeners)
            listener.onTouch(ev);
        return super.dispatchTouchEvent(ev);
    }
    public interface MyOnTouchListener {
        public void onTouch(MotionEvent ev);
    }
    

    OnSwipeTouchListener:

    public class OnSwipeTouchListener{
    
    private final GestureDetector gestureDetector;
    
    public OnSwipeTouchListener (Context ctx){
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }
    
    private final class GestureListener extends SimpleOnGestureListener {
         //override touch methode like ondown ... 
         //and call the impelinfragment()
    }
    public void impelinfragment(){
     //this method impelment in fragment
    }
    //by calling this mehod pass touch to detector
    public void onTouch( MotionEvent event) {
         gestureDetector.onTouchEvent(event);
    }
    

    And add this code to fragment you like to dispach touch in it:

    //ontouch listenr
    MainActivity.MyOnTouchListener onTouchListener;
    private OnSwipeTouchListener touchListener=new OnSwipeTouchListener(getActivity()) {
        public void impelinfragment(){
     //do what you want:D
    }
    
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        //setting for on touch listener
        ((MainActivity)getActivity()).registerMyOnTouchListener(new MainActivity.MyOnTouchListener() {
            @Override
            public void onTouch(MotionEvent ev) {
                LocalUtil.showToast("i got it ");
                touchListener.onTouch(ev);
            }
        });
    }
    

    I use this method to get all swipe to right or left event in fragment without conflicting with other elem in page .unlike rax answer

提交回复
热议问题