如何以编程方式触发android中的触摸事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23902892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:34:43  来源:igfitidea点击:

How to programmatically trigger the touch event in android?

androidtouchgesture-recognitiongestures

提问by user782104

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)

首先手指在屏幕的 (0,50%) 处向下触摸并滑动到屏幕的 (50%,50%),然后退出(将手指移出屏幕)

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.

但是,如何模拟上述情况?我需要创建 2 个事件吗?onTouchDown , onMove 等....?谢谢你的帮助。

回答by bstar55

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

回答by SubqueryCrunch

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

PS:这是一个 xamarin android 解决方案,但您可以轻松地为 java 修改它