簡體   English   中英

Android:如何創建 MotionEvent?

[英]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_DOWNACTION_MOVEACTION_UPACTION_CANCEL之一。
  • x此事件的 X 坐標。
  • y此事件的 Y 坐標。
  • metaState生成事件時有效的任何元/修飾鍵的 state。

鏈接到 API 文檔

補充答案

這是一個說明已接受答案的示例:

// 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM