![](/img/trans.png)
[英]How to create a MotionEvent for unit testing in Android Studio?
[英]Android: How to create a MotionEvent?
MotionEvent 没有构造函数,我想在我的单元测试中手动创建一个 MotionEvent,那么如何获得呢? 谢谢。
您应该使用 MotionEvent class 的MotionEvent
obtain
方法之一来创建新事件。
最简单的方法(除了从现有事件包装新事件)是:
static public MotionEvent obtain(long downTime, long eventTime, int action,
float x, float y, int metaState) {
API 文档:
创建一个新的 MotionEvent,填充基本运动值的子集。 此处未指定的是:设备 id(始终为 0)、压力和大小(始终为 1)、x 和 y 精度(始终为 1)和 edgeFlags(始终为 0)。
参数:
downTime
用户最初按下以启动 position 事件的 stream 的时间(以毫秒为单位)。 这必须从 SystemClock.uptimeMillis() 获得。eventTime
生成此特定事件的时间(以毫秒为单位)。 这必须从SystemClock.uptimeMillis()
获得。action
正在执行的操作类型—— ACTION_DOWN
、 ACTION_MOVE
、 ACTION_UP
或ACTION_CANCEL
之一。x
此事件的 X 坐标。y
此事件的 Y 坐标。metaState
生成事件时有效的任何元/修饰键的 state。这是一个说明已接受答案的示例:
// get the coordinates of the view
int[] coordinates = new int[2];
myView.getLocationOnScreen(coordinates);
// MotionEvent parameters
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis();
int action = MotionEvent.ACTION_DOWN;
int x = coordinates[0];
int y = coordinates[1];
int metaState = 0;
// dispatch the event
MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, x, y, metaState);
myView.dispatchTouchEvent(event);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.