Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to create a MotionEvent?

Tags:

android

events

MotionEvent doesn't get a constructor, I wanted to manually create a MotionEvent in my unit test, then how to get that? Thanks.

like image 946
fifth Avatar asked May 03 '11 08:05

fifth


People also ask

What is MotionEvent in Android?

Overview. Motion events describe movements in terms of an action code and a set of axis values. The action code specifies the state change that occurred such as a pointer going down or up. The axis values describe the position and other movement properties.

How do you create a motion event?

You should use one of the static obtain methods of the MotionEvent class to create a new event. API Docs: Create a new MotionEvent, filling in a subset of the basic motion values. Those not specified here are: device id (always 0), pressure and size (always 1), x and y precision (always 1), and edgeFlags (always 0).

How do I use onTouchEvent on Android?

After the Math. abs() calls, you're essentially testing if their finger is farther down the screen than it is across the screen. Store the initial down coordinates as member variables and set them during ACTION_DOWN . You declared two floats (touchX and touchY) inside the onTouchEvent method.

Which method you should override to control your touch action?

To make sure that each view correctly receives the touch events intended for it, override the onInterceptTouchEvent() method.


1 Answers

You should use one of the static obtain methods of the MotionEvent class to create a new event.

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:

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

Parameters:

  • downTime The time (in ms) when the user originally pressed down to start a stream of position events. This must be obtained from SystemClock.uptimeMillis().
  • eventTime The the time (in ms) when this specific event was generated. This must be obtained from SystemClock.uptimeMillis().
  • action The kind of action being performed -- one of either ACTION_DOWN, ACTION_MOVE, ACTION_UP, or ACTION_CANCEL.
  • x The X coordinate of this event.
  • y The Y coordinate of this event.
  • metaState The state of any meta / modifier keys that were in effect when the event was generated.

Link to API Docs

like image 130
rekaszeru Avatar answered Oct 09 '22 05:10

rekaszeru