Search code examples
androidtouch-eventsimulatemotionevent

I want to call onTouchEvent(MotionEvent event) whithin my code with a different MotionEvent object?


I want to simulate a touch event in code, in other words, a sweep on the screen.

I want to trigger the method public boolean onTouchEvent(MotionEvent event) inside my code, but the MotionEvent object should have the needed values in order to simulate a sweep on the screen (e.g. a sweep from the left to the right).

I read this entry, but I think this is only useful when making Android Unit Tests, and I need to call this method from any part of my code to simulate the swipe anytime I want.

I want to know if this is possible. Thanks in advance.


Solution

  • How to simulate a touch event in Android?

    MotionEvent motionEvent = MotionEvent.obtain(
        downTime, 
        eventTime, 
        MotionEvent.ACTION_UP, 
        x, 
        y, 
        metaState
    );
    
    // Dispatch touch event to view
    view.dispatchTouchEvent(motionEvent);