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

StackOverflow https://stackoverflow.com/questions/17215788

Domanda

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.

È stato utile?

Soluzione

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);

Altri suggerimenti

Thank Diogo Bento. And there is something about my code: it is not a OnTouchEvent. It is a GestureDetector.OnGestureListener. And I try to call onSingelTapUp().

long time =System.currentTimeMillis();
MotionEvent motionEvent = MotionEvent.obtain( time, time+1, MotionEvent.ACTION_DOWN, 0, 0, 0);
view.last.dispatchTouchEvent(motionEvent);
MotionEvent motionEvent1 = MotionEvent.obtain( time+1, time+2, MotionEvent.ACTION_UP, 0, 0, 0);
view.dispatchTouchEvent(motionEvent1);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top