简体   繁体   English

Android:如何创建 MotionEvent?

[英]Android: How to create a MotionEvent?

MotionEvent doesn't get a constructor, I wanted to manually create a MotionEvent in my unit test, then how to get that? MotionEvent 没有构造函数,我想在我的单元测试中手动创建一个 MotionEvent,那么如何获得呢? Thanks.谢谢。

You should use one of the static obtain methods of the MotionEvent class to create a new event.您应该使用 MotionEvent class 的MotionEvent obtain方法之一来创建新事件。

The simplest way (besides wrapping a new event from an existing one) is:最简单的方法(除了从现有事件包装新事件)是:

static public MotionEvent obtain(long downTime, long eventTime, int action,
        float x, float y, int metaState) {

API Docs : API 文档

Create a new MotionEvent, filling in a subset of the basic motion values.创建一个新的 MotionEvent,填充基本运动值的子集。 Those not specified here are: device id (always 0), pressure and size (always 1), x and y precision (always 1), and edgeFlags (always 0).此处未指定的是:设备 id(始终为 0)、压力和大小(始终为 1)、x 和 y 精度(始终为 1)和 edgeFlags(始终为 0)。

Parameters :参数

  • downTime The time (in ms) when the user originally pressed down to start a stream of position events. downTime用户最初按下以启动 position 事件的 stream 的时间(以毫秒为单位)。 This must be obtained from SystemClock.uptimeMillis().这必须从 SystemClock.uptimeMillis() 获得。
  • eventTime The the time (in ms) when this specific event was generated. eventTime生成此特定事件的时间(以毫秒为单位)。 This must be obtained from SystemClock.uptimeMillis() .这必须从SystemClock.uptimeMillis()获得。
  • action The kind of action being performed -- one of either ACTION_DOWN , ACTION_MOVE , ACTION_UP , or ACTION_CANCEL . action正在执行的操作类型—— ACTION_DOWNACTION_MOVEACTION_UPACTION_CANCEL之一。
  • x The X coordinate of this event. x此事件的 X 坐标。
  • y The Y coordinate of this event. y此事件的 Y 坐标。
  • metaState The state of any meta / modifier keys that were in effect when the event was generated. metaState生成事件时有效的任何元/修饰键的 state。

Link to API Docs 链接到 API 文档

Supplemental answer补充答案

Here is an example illustrating the accepted answer:这是一个说明已接受答案的示例:

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

Notes笔记

  • Other meta states include things like KeyEvent.META_SHIFT_ON , etc.其他元状态包括KeyEvent.META_SHIFT_ON等。
  • Thanks to this answer for help with the example.感谢此答案对示例的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM