How to programmatically trigger the touch event in android?

这一生的挚爱 提交于 2019-11-26 09:34:40

问题


I would like to trigger a touch event like this:

First the finger is touch down at the (0,50%) of the screen and slide to the (50%,50%) of the screen, and exit (move the finger off the screen)

I have found some thing like this:

MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, x, y, pressure, size, metaState, xPrecision, yPrecision, deviceId, edgeFlags);

onTouchEvent(event);

However, how to emulate the above case? Do I need to create 2 event ? onTouchDown , onMove etc.... ? Thanks for helping.


回答1:


// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here:     developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
    downTime, 
    eventTime, 
    MotionEvent.ACTION_UP, 
    x, 
    y, 
    metaState
);

// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);



回答2:


And here is the clean version:

public void TouchView(View view)
{
    view.DispatchTouchEvent(MotionEvent.Obtain(SystemClock.UptimeMillis(), SystemClock.UptimeMillis(), (int)MotionEventActions.Down, 0, 0, 0));
    view.DispatchTouchEvent(MotionEvent.Obtain(SystemClock.UptimeMillis(), SystemClock.UptimeMillis(), (int)MotionEventActions.Up, 0, 0, 0));
}

PS: This is a xamarin android solution but you can easily modify it for java



来源:https://stackoverflow.com/questions/23902892/how-to-programmatically-trigger-the-touch-event-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!