我想触发这样的触摸事件:
首先,手指在屏幕的(0,50%)处向下触摸并滑动到屏幕的(50%,50%),然后退出(将手指从屏幕上移开)
我发现了这样的事情:
MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, x, y, pressure, size, metaState, xPrecision, yPrecision, deviceId, edgeFlags);
onTouchEvent(event);
但是,如何模仿上述情况?我需要创建2个活动吗? onTouchDown,onMove等....?谢谢你的帮助。
答案 0 :(得分:78)
// 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);
答案 1 :(得分:1)
这是干净的版本:
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:这是一个xamarin android解决方案,但是您可以轻松地针对Java对其进行修改
答案 2 :(得分:0)
要添加到上面@ bstar55的出色答案中-如果您想要创建一个“轻击”事件(例如,用户点击视图),则需要模拟用户触摸屏幕然后移除他们的屏幕手指在短时间内。
为此,您需要“分派” ACTION_DOWN MotionEvent,然后在短时间后紧跟ACTION_UP MotionEvent。
以下示例在Kotlin中经过测试并可靠地工作:
//Create amd send a tap event at the current target loctaion to the PhotoView
//From testing (on an original Google Pixel) a tap event needs an ACTION_DOWN followed shortly afterwards by
//an ACTION_UP, so send both events
//First, create amd send the ACTION_DOWN MotionEvent
var originalDownTime: Long = SystemClock.uptimeMillis()
var eventTime: Long = SystemClock.uptimeMillis() + 100
var x = your_X_Value
var y = your_Y_Value
var metaState = 0
var motionEvent = MotionEvent.obtain(
originalDownTime,
eventTime,
MotionEvent.ACTION_DOWN,
x,
y,
metaState
)
var returnVal = yourView.dispatchTouchEvent(motionEvent)
Log.d(TAG,"rteurnVal: " + returnVal)
//Create amd send the ACTION_UP MotionEvent
eventTime= SystemClock.uptimeMillis() + 100
motionEvent = MotionEvent.obtain(
originalDownTime,
eventTime,
MotionEvent.ACTION_UP,
x,
y,
metaState
)
returnVal = yourView.dispatchTouchEvent(motionEvent)
Log.d(TAG,"rteurnVal: " + returnVal)