Android: How to create a MotionEvent?

MotionEvent does not get a constructor, I wanted to manually create a MotionEvent in my unit test, and then how to get it? Thank.

+43
android events
May 03 '11 at 8:40
source share
2 answers

To create a new event, you must use one of the static obtain methods of the obtain class.

The easiest way (in addition to wrapping a new event from an existing one):

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

API docs :

Create a new MotionEvent by filling out a subset of the basic motion values. Those that are not listed here: id device (always 0), pressure and size (always 1), x and y precision (always 1), and edgeFlags (always 0).

Parameters :

  • downTime time (in ms) when the user first clicked the position event stream. This should be obtained from SystemClock.uptimeMillis ().
  • eventTime time (in ms) when this particular event was generated. This should be obtained from SystemClock.uptimeMillis() .
  • action The type of action performed is one of ACTION_DOWN , ACTION_MOVE , ACTION_UP or ACTION_CANCEL .
  • x X coordinate of this event.
  • y The y coordinate of this event.
  • metaState state of any meta / modifiers that acted when the event was created.

API Document Reference

+75
May 03 '11 at 8:49
source share

Additional 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.
  • Thanks for this answer for the help in this example.
+1
Oct 07 '17 at 8:09
source share



All Articles