What you’ll study
- What a
MotionEventis: every pointer at one moment, plus the samples since the last event. - The actions, and how one gesture becomes a sequence of events.
- Pointer index versus pointer ID, and why anything keyed by index breaks.
- History: the samples bundled into one move.
- The axes: position, pressure, size, orientation, tilt, distance, and which devices report them.
- Tools, buttons, hover and cancel: finger, pen and eraser, the barrel button, and
FLAG_CANCELED. - What Compose’s
PointerInputChangekeeps from all this, and what you have to go back to theMotionEventfor.
How it connects
Guide 1 used the MotionEvent in a few lines: history,
multiple pointers, a cancel flag. Guide 4 followed a touch
from the glass to the app and showed where the bundling comes from. This guide reads the object that
arrives. The next one is about what to do with the samples: smoothing and predicting the pen.
Read it at your level
| Level | Read | You should be able to |
|---|---|---|
| Student | The basics, the pointer table | Say what a MotionEvent contains and why a second finger changes the event |
| Fresher | + The high level, actions | Handle down, move and up for several fingers without mixing them up |
| Junior | + Index versus ID, history, axes | Key strokes by pointer ID, read every sample, and read pressure and tilt |
| Mid | + Tools, hover, cancel, Compose | Tell pen from finger from eraser, handle hover, and drop cancelled strokes |
| Senior | + Edge cases, cross questions | Reason about devices, IDs and what each layer of the stack promises |
The basics
A touch gesture reaches your view as a stream of MotionEvents: one when the first finger lands, more as
fingers move, come and go, and a last one when the final finger lifts. Each event is a snapshot of
every pointer (a finger, a pen, a mouse) at one moment, plus an action that says what just changed.
This function prints what an event holds. Call it from onTouchEvent() and read the log while you touch
the screen:
fun describe(e: MotionEvent): String = buildString {
append(MotionEvent.actionToString(e.actionMasked))
if (e.actionMasked == MotionEvent.ACTION_POINTER_DOWN || e.actionMasked == MotionEvent.ACTION_POINTER_UP) {
append(" actionIndex=${e.actionIndex}")
}
append(" history=${e.historySize}")
for (i in 0 until e.pointerCount) {
append("\n index=$i id=${e.getPointerId(i)} tool=${e.getToolType(i)} x=${e.getX(i)} y=${e.getY(i)} pressure=${e.getPressure(i)}")
}
}
Put two fingers down and lift the first one. The pointer table below does the same on a model, and shows the one thing that surprises people: a pointer’s index changes, its ID doesn’t.
Try it: the pointer table
The fingers of a touchscreen, one sample at a time, turned into the events your code receives. Pick a
scenario and press Next. Each event is the table onTouchEvent() sees: the pointer’s index in this
event, its ID, and its position. The last column follows each pointer’s point to the stroke your code
puts it in, when it finds strokes by pointer index or by pointer ID.
Things to try: in The middle finger lifts, step to sample 5 with pointer index selected. C’s index
dropped from 2 to 1, so its points find no stroke. Switch to pointer ID: the same events, every point
in the right stroke. Then step on to sample 7, where D lands in the gap and takes the ID B had. In
The first finger lifts, C’s points end up in B’s stroke. In A palm lands while a finger draws,
look at the FLAG_CANCELED chip on the event for sample 4.
The table models the system’s code for one touchscreen, quoted below. It is not a recording of a device.
The high level
An event has three layers:
| Layer | What it holds | Read with |
|---|---|---|
| The event | the action, which pointer the action is about, down time and event time, flags, button state, source and device, classification | getActionMasked(), getActionIndex(), getDownTime(), getEventTime(), getFlags(), getButtonState(), getSource(), getDeviceId(), getClassification() |
| Each pointer | its ID, its tool, its position, and its axes: pressure, size, touch major and minor, orientation, tilt, distance | getPointerId(i), getToolType(i), getX(i), getAxisValue(axis, i) |
| The history | the same readings at earlier times, for a move | getHistorySize(), getHistoricalEventTime(h), getHistoricalAxisValue(axis, i, h) |
Almost every per-pointer method takes the pointer index. The index runs from 0 to
getPointerCount() - 1, and the documentation says what it is for: reading the arrays in this event.
The pointer ID is for recognising the same finger in the next one.
The low level
Excerpts are from AOSP main and AndroidX androidx-main unless noted, trimmed with …. Links are in
The map below.
1. Actions: one gesture, several kinds of event
| Action | When | Which pointer |
|---|---|---|
ACTION_DOWN |
the first pointer touches | index 0 |
ACTION_POINTER_DOWN |
another pointer touches while one is down | getActionIndex() |
ACTION_MOVE |
at least one pointer moved | all of them; no action index |
ACTION_POINTER_UP |
a pointer leaves while others stay | getActionIndex(); it is still listed in this event |
ACTION_UP |
the last pointer leaves | index 0 |
ACTION_CANCEL |
the gesture was aborted | all pointers are up |
ACTION_HOVER_ENTER, _MOVE, _EXIT |
a pen or mouse is over the screen, not touching | the hovering pointer; delivered to onGenericMotionEvent() |
ACTION_BUTTON_PRESS, _RELEASE |
a mouse or stylus button changed | getActionButton(); also onGenericMotionEvent() |
One int carries two things: the action in the low byte (ACTION_MASK, 0xff) and, for
ACTION_POINTER_DOWN and ACTION_POINTER_UP, the pointer index in the next byte
(ACTION_POINTER_INDEX_MASK, shifted by ACTION_POINTER_INDEX_SHIFT, which is 8).
getActionMasked() returns the action alone; getActionIndex() returns the index; getAction() returns
both packed together, which is why a bare getAction() == ACTION_POINTER_UP check only matches when the
pointer happens to be at index 0, and silently fails for the others.
The system builds that int in TouchInputMapper::dispatchMotion(). It also decides when a “pointer”
action is really the first or last one:
uint32_t pointerCount = 0;
while (!idBits.isEmpty()) {
uint32_t id = idBits.clearFirstMarkedBit();
uint32_t index = idToIndex[id];
pointerProperties.push_back(properties[index]);
pointerCoords.push_back(coords[index]);
if (changedId >= 0 && id == uint32_t(changedId)) {
action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
}
pointerCount++;
}
…
if (changedId >= 0 && pointerCount == 1) {
// Replace initial down and final up action.
…
}
When a finger is the only one in the event, POINTER_DOWN becomes DOWN and POINTER_UP becomes UP
(or CANCEL, below). The loop also decides the order of the pointers, which is the next section.
In dispatchTouches() the same file decides which events one touch sample produces. If the same
pointers are down as in the last sample, the comment says it all: “No pointer id changes so this is a
move event”, and that MOVE is sent whether or not a position changed. If pointers came or went, then
in this order: a POINTER_UP for each pointer that left, one MOVE for the rest if one of them moved,
and a POINTER_DOWN for each pointer that landed. That is why one change of fingers can reach you as
two or three events in a row, and why the table above shows several events for a single sample.
Handle every action, and always ACTION_CANCEL:
class ActionExample(context: Context) : View(context) {
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> { /* the first pointer is down: start the gesture */ }
MotionEvent.ACTION_POINTER_DOWN -> { val i = event.actionIndex /* another pointer is down, at index i */ }
MotionEvent.ACTION_MOVE -> { /* loop over pointerCount: every pointer is in this event */ }
MotionEvent.ACTION_POINTER_UP -> { val i = event.actionIndex /* pointer i is leaving; it is still in this event */ }
MotionEvent.ACTION_UP -> { /* the last pointer is up */ }
MotionEvent.ACTION_CANCEL -> { /* the gesture is over: throw the work away */ }
}
return true
}
}
2. Pointer index versus pointer ID
The documentation states the rule in one paragraph: the order of pointers in an event is undefined, so a pointer’s index can change from one event to the next, while its ID “is guaranteed to remain constant as long as the pointer remains active”. Use the ID to follow a finger, and the index to read values.
You don’t have to take the “can change” on trust. This is how the touchscreen mapper gives a new contact
its ID (MultiTouchInputMapper::syncTouch()):
// Assign pointer id using tracking id if available.
if (mHavePointerIds) {
const int32_t trackingId = inSlot.getTrackingId();
int32_t id = -1;
if (trackingId >= 0) {
for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty();) {
uint32_t n = idBits.clearFirstMarkedBit();
if (mPointerTrackingIdMap[n] == trackingId) {
id = n;
break;
}
}
if (id < 0 && !mPointerIdBits.isFull()) {
id = mPointerIdBits.markFirstUnmarkedBit();
mPointerTrackingIdMap[id] = trackingId;
}
}
…
A contact the mapper already knows (by its kernel tracking ID, from guide 4) keeps its pointer ID. A new
one takes markFirstUnmarkedBit(): the lowest ID not in use. And the loop in dispatchMotion() above
walks the IDs with clearFirstMarkedBit(), lowest first, so the index is the rank of the ID among the
pointers in that event. Put together:
- Three fingers land: IDs 0, 1, 2, at indexes 0, 1, 2.
- The middle one (ID 1) lifts: the others keep IDs 0 and 2, but the last one is now at index 1.
- A new finger lands: it takes the lowest free ID, 1, and is index 1. The last finger is back at index 2.
That is the scenario The middle finger lifts in the table above, run by the source. (In The first finger lifts, every remaining finger’s index drops by one.) Two more consequences:
- An ID is only valid while its pointer is down. The next finger can have the same one. Forget a pointer’s state when it goes up.
- IDs belong to a device.
InputDispatcherkeeps its touch state per device: itsTouchStatetakes adeviceIdin nearly every call. A touchscreen and a pen digitizer, if they are separate devices, each have their own pointer 0 and send their own events. If a view takes both, key strokes by(event.deviceId, pointerId).
The documentation promises less than the code does, so write code that needs only the promise: store anything per pointer under its ID.
class StrokeView(context: Context) : View(context) {
private val strokes = SparseArray<Path>() // key: pointer ID, never index
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
val i = event.actionIndex
strokes.put(event.getPointerId(i), Path().apply { moveTo(event.getX(i), event.getY(i)) })
}
MotionEvent.ACTION_MOVE -> for (i in 0 until event.pointerCount) {
strokes.get(event.getPointerId(i))?.lineTo(event.getX(i), event.getY(i))
}
MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_UP -> strokes.remove(event.getPointerId(event.actionIndex))
MotionEvent.ACTION_CANCEL -> strokes.clear()
}
invalidate()
return true
}
}
To go the other way, from an ID you saved to its index in the current event, ask for it. -1 means that
pointer isn’t in this event:
fun xOf(event: MotionEvent, pointerId: Int): Float? {
val index = event.findPointerIndex(pointerId)
return if (index >= 0) event.getX(index) else null
}
3. History: the samples in one move
Guide 4 showed where it comes from: touch samples are batched until the next frame. What arrives is one
ACTION_MOVE that carries the newest sample as its current values, and the earlier ones as history.
The reference states the scope: “This only applies to ACTION_MOVE events”, all other actions have a
history size of 0. (A hover move bundles its intermediate points too, as its documentation says.)
The rule is in the class documentation: to process every coordinate in time order, first consume the historical ones, then the current ones. For all pointers:
fun forEachSample(e: MotionEvent, block: (time: Long, index: Int, x: Float, y: Float, pressure: Float) -> Unit) {
for (h in 0 until e.historySize) {
for (i in 0 until e.pointerCount) {
block(e.getHistoricalEventTime(h), i, e.getHistoricalX(i, h), e.getHistoricalY(i, h), e.getHistoricalPressure(i, h))
}
}
for (i in 0 until e.pointerCount) {
block(e.eventTime, i, e.getX(i), e.getY(i), e.getPressure(i))
}
}
The documentation adds a warning that matters for gestures and mice: for relative axes (such as
AXIS_RELATIVE_X, API 24) every sample counts, because “these relative values are not accumulated in a
batched event”. Skip the history and you lose movement.
From API 35, some of those samples may be computed rather than measured: PointerCoords.isResampled(),
from guide 4.
4. The axes
An axis is one kind of reading. getX() and getY() are two of them; getAxisValue(axis, i) reads
any. The ones that matter for drawing, with the units the reference gives:
| Axis | What it is | Range and units |
|---|---|---|
AXIS_X, AXIS_Y |
position, relative to the view that received the event | pixels; getRawX(i) (API 29) gives display coordinates |
AXIS_PRESSURE |
pressure on the surface | 0 to 1 “normal pressure”, “although values higher than 1 may be generated”; a mouse gives 1 with the primary button pressed, else 0 |
AXIS_SIZE |
size of the contact, relative to the largest the device can detect | 0 to 1, “not a linear scale”; use touch major for calibrated size |
AXIS_TOUCH_MAJOR, AXIS_TOUCH_MINOR |
the contact as an ellipse | display pixels on a touchscreen; device units on a touchpad; equal when circular |
AXIS_TOOL_MAJOR, AXIS_TOOL_MINOR |
the approaching finger or tool | may be larger than the touch, as the tool may not fully touch |
AXIS_ORIENTATION |
which way the contact points | touch: -π/2 to π/2, 0 is up; stylus: -π to π, 0 is pointing up, π/2 is right |
AXIS_TILT |
stylus angle | 0 is perpendicular to the surface, π/2 is flat against it |
AXIS_DISTANCE |
stylus distance from the screen | 0 is contact; larger is further away |
Not every device reports every axis. getAxisValue() returns “0 if the axis is not available”, which you
can’t tell from a real zero. Ask the device which axes it has:
fun reports(e: MotionEvent, axis: Int): Boolean = e.device?.getMotionRange(axis, e.source) != null
fun axes(e: MotionEvent, i: Int): String = listOf(
MotionEvent.AXIS_PRESSURE, MotionEvent.AXIS_SIZE, MotionEvent.AXIS_TOUCH_MAJOR, MotionEvent.AXIS_TOUCH_MINOR,
MotionEvent.AXIS_ORIENTATION, MotionEvent.AXIS_TILT, MotionEvent.AXIS_DISTANCE,
).joinToString { axis -> "${MotionEvent.axisToString(axis)}=${e.getAxisValue(axis, i)}" }
Which axes exist follows the hardware from guide 4. Pens are the ones that add pressure, and, depending on the device, tilt and hover distance; an infrared frame reports a contact size and has no way to measure pressure. The same app sees different data on different devices, so check, and fall back.
Try it: the pointer pad
The same readings, from your own device. Touch the box with fingers, a pen, a mouse, or several at once.
It uses the browser’s counterpart of MotionEvent, the Pointer Events API, so some names differ.
| Web | Android |
|---|---|
pointerId |
pointer ID (the browser picks its own numbers, so don’t expect the same ones) |
pointerType: mouse, pen, touch |
tool type: MOUSE, STYLUS (and ERASER), FINGER |
pressure, 0 to 1 |
AXIS_PRESSURE |
tiltX, tiltY, in degrees from -90 to 90 |
AXIS_TILT and AXIS_ORIENTATION, in radians |
width, height, in CSS pixels, “1” if the hardware can’t say |
contact size: AXIS_TOUCH_MAJOR and AXIS_TOUCH_MINOR |
getCoalescedEvents() |
historical samples |
buttons & 32: pen eraser button |
TOOL_TYPE_ERASER |
Things to try: draw fast with a finger and compare events with samples in the line below the pad: that ratio is the history. Hover a pen over it before touching and watch the state column say hover. On a mouse, hold the button and look at the pressure: the web reports 0.5 while a button is down, Android 1.0. Rows for pointers that left stay greyed until the next touch, so you can read their last values.
5. Tools, buttons and hover
Each pointer has a tool type, read per pointer with getToolType(i):
| Constant | Means |
|---|---|
TOOL_TYPE_FINGER |
a finger |
TOOL_TYPE_STYLUS |
a stylus |
TOOL_TYPE_ERASER |
“an eraser or a stylus being used in an inverted posture” |
TOOL_TYPE_MOUSE |
a mouse |
TOOL_TYPE_UNKNOWN |
the tool isn’t known, or doesn’t matter (a trackball, say) |
Because it is per pointer, one event can hold a stylus and a finger. A passive stylus (guide 4) reports
as a finger. Buttons are in getButtonState(), a bit mask: BUTTON_STYLUS_PRIMARY (API 23) is the pen’s
barrel button. The class documentation suggests checking the button state on ACTION_DOWN, since a touch
that starts with a button held may mean something else, such as a menu. A change of a button arrives
as ACTION_BUTTON_PRESS or ACTION_BUTTON_RELEASE, with getActionButton() saying which.
fun isErasing(e: MotionEvent, i: Int): Boolean = e.getToolType(i) == MotionEvent.TOOL_TYPE_ERASER
fun barrelPressed(e: MotionEvent): Boolean = (e.buttonState and MotionEvent.BUTTON_STYLUS_PRIMARY) != 0
Hover is a pen near the screen, or a mouse over it, without touching. For a stylus it means “hovering
over the screen or drawing tablet but has not touched it”. Hover events are not touch events, so they go
to onGenericMotionEvent(), not onTouchEvent(). That is the answer to “my hover preview never shows”:
class HoverView(context: Context) : View(context) {
override fun onGenericMotionEvent(event: MotionEvent): Boolean {
if (event.isFromSource(InputDevice.SOURCE_STYLUS) && event.actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
val distance = event.getAxisValue(MotionEvent.AXIS_DISTANCE) // 0 is touching; larger is further away
Log.d("Hover", "pen at ${event.x}, ${event.y}, distance $distance")
return true
}
return super.onGenericMotionEvent(event)
}
}
When the pen touches down, the hover ends: the mapper sends ACTION_HOVER_EXIT as soon as there are
touching pointers.
6. Cancel
Two shapes, one meaning: this gesture, or this pointer, was a mistake; don’t act on it.
ACTION_CANCEL: “The current gesture has been aborted.” You get no more points, and “you should assume that all pointers that were down have been lifted”.ACTION_POINTER_UPwithFLAG_CANCELED: when only one pointer is cancelled, the others stay down. The flag exists from API 33, and the documentation says what it is for: an “unintentional user touch”, such as a grip or a palm on the screen; “end of drawing” should be aborted.
The mapper turns one into the other by how many pointers are left:
bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
…
out.push_back(dispatchMotion(…, AMOTION_EVENT_ACTION_POINTER_UP, 0,
isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, …));
…
// in dispatchMotion(), when it was the only pointer:
if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
action = AMOTION_EVENT_ACTION_CANCEL;
} else {
action = AMOTION_EVENT_ACTION_UP;
}
The palm-rejection stage from guide 4 sets the same flag. One helper covers both shapes:
fun MotionEvent.isCancelled(): Boolean =
actionMasked == MotionEvent.ACTION_CANCEL ||
(Build.VERSION.SDK_INT >= 33 && (flags and MotionEvent.FLAG_CANCELED) != 0)
An ink view uses it at ACTION_POINTER_UP and ACTION_UP: if the event is cancelled, drop that pointer’s
stroke instead of committing it. On releases before API 33 there is no flag, so only ACTION_CANCEL
can be recognised.
7. The same thing in Compose
Compose turns every MotionEvent into a PointerEvent with a list of PointerInputChanges. Most of
what you read above is there, under other names, and some of it is not:
MotionEvent |
Compose |
|---|---|
getPointerId(i) |
change.id: Compose’s own PointerId, counting up from 0 for each new pointer. It is not the MotionEvent ID, and it is not reused |
getX(i), getY(i) |
change.position, in the composable’s coordinates |
| down and up | change.pressed, change.previousPressed; changedToDown(), changedToUp() |
getPressure(i) |
change.pressure |
getEventTime() |
change.uptimeMillis, with previousUptimeMillis and previousPosition |
getToolType(i) |
change.type: PointerType.Touch, Mouse, Stylus, Eraser, Unknown |
| history | change.historical: a list of HistoricalChange, each with time and position (plus trackpad gesture fields) |
getButtonState(), getClassification() |
event.buttons, event.classification |
| tilt, orientation, distance, touch size, per-sample pressure | not in the change: read the MotionEvent |
ACTION_CANCEL |
a synthesized event where every pressed pointer is released and the change is consumed |
ACTION_POINTER_UP with FLAG_CANCELED |
not marked: read event.motionEvent?.flags |
Three of these deserve a line each.
IDs. MotionEventAdapter keeps a map from the MotionEvent’s pointer ID to a Compose ID that
counts up (nextId++). Don’t compare change.id.value with getPointerId().
Cancel. For ACTION_CANCEL the adapter returns null, and AndroidComposeView calls
processCancel(); the pointer-input node then synthesizes an event “where all previously down pointers
are now up, the change in down-ness is consumed”. changedToUp() is defined as
!isConsumed && previousPressed && !pressed, so it is false for that event. A stroke that commits on
changedToUp() is not committed on cancel; code that commits on “no longer pressed” is. Nothing
tells the first kind that its stroke is over, so also handle the released-but-consumed case, as the
last snippet below does, and drop the open stroke there. (A release that another handler consumed
looks the same, which is the right outcome: the stroke isn’t yours to commit.) For the
single-pointer cancel (FLAG_CANCELED) I found no handling in AndroidComposeView,
MotionEventAdapter, PointerEvent.android.kt or SuspendingPointerInputFilter, so Compose does not
mark it, and you have to read the flag yourself.
The MotionEvent behind it. On Android, PointerEvent.motionEvent gives you the original, for
exactly this: “supplemental metadata”. Its documentation says it is read-only, must not be stored, and
is not meant for primary input handling, and it can be null (for events Compose made up, and after
the event was dispatched).
Don’t pair a change with a MotionEvent pointer by index. The adapter does list pointers in the
MotionEvent’s order, but the changes that reach your pointerInput block are rebuilt for each node
in HitPathTracker: keyed by Compose’s own pointer ID, so in order of arrival, and only the pointers
that hit that node. Android lists the lowest free ID first, so after A lifts and a new finger D lands,
the MotionEvent has D then B, and Compose has B then D. The two lists can have the same size and
different order, which makes a size check useless. Pair them by what they are, and expect one stylus:
fun Modifier.penInput(onSample: (position: Offset, pressure: Float, tilt: Float) -> Unit): Modifier =
pointerInput(Unit) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
val motion = event.motionEvent ?: continue
val pen = event.changes.singleOrNull { it.type == PointerType.Stylus && it.pressed } ?: continue
val index = (0 until motion.pointerCount).singleOrNull { motion.getToolType(it) == MotionEvent.TOOL_TYPE_STYLUS } ?: continue
onSample(pen.position, pen.pressure, motion.getAxisValue(MotionEvent.AXIS_TILT, index))
}
}
}
If you need data for several pens at once, there is no safe pairing from the change alone, so compare positions as a last resort and don’t trust it.
And the stroke bookkeeping of section 2, in Compose, with history:
fun Modifier.strokeInput(
onStart: (PointerId) -> Unit,
onPoint: (PointerId, Offset) -> Unit,
onCommit: (PointerId) -> Unit,
onDrop: (PointerId) -> Unit,
): Modifier =
pointerInput(Unit) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
for (change in event.changes) {
when {
change.changedToDown() -> { onStart(change.id); onPoint(change.id, change.position) }
change.changedToUp() -> onCommit(change.id) // a normal lift
change.previousPressed && !change.pressed -> onDrop(change.id) // a consumed release: a cancel, or taken by another handler
change.pressed && change.positionChanged() -> {
for (sample in change.historical) onPoint(change.id, sample.position) // earlier samples first
onPoint(change.id, change.position)
}
}
}
}
}
}
Everything from guide 1 still applies: the history is there, in time order, and a touch that was a palm should not become a stroke.
Checkpoint
You should be able to say:
- An event is every pointer at one moment, plus an action;
ACTION_MOVEalso carries history. ACTION_POINTER_DOWNandACTION_POINTER_UPcarry the pointer index;getActionMasked()andgetActionIndex()unpack it.- Index is a place in this event’s list; ID is the finger, while it is down. Key by ID.
- The system gives a new contact the lowest free ID and lists pointers by ID, so indexes shift when a finger leaves.
- Read the history first, then the current values; check an axis exists before trusting it.
- Hover goes to
onGenericMotionEvent(). ACTION_CANCELand a cancelledACTION_POINTER_UPmean “don’t commit”.- Compose has its own IDs, keeps time and position of history only, and needs
motionEventfor tilt, distance and size.
Why it helps
| Symptom | What is happening | What to do |
|---|---|---|
| A second finger makes the first stroke jump, or points vanish when one finger lifts | Strokes are stored by pointer index, which shifts when a finger leaves | Key by getPointerId(i); delete the entry on up |
| A stray mark where the palm rested | The cancel was ignored and the stroke committed | Drop the pointer’s stroke on ACTION_CANCEL and on FLAG_CANCELED |
| Pressure is 1.0 or 0 for every point | The device has no pressure axis, the tool is a finger, or it is a mouse | Check getMotionRange() and the tool type; fall back to a fixed width |
| The pen preview never appears | Hover goes to onGenericMotionEvent() |
Override it; look for ACTION_HOVER_MOVE |
| Tilt is always 0 | The device doesn’t report it, or Compose’s change doesn’t carry it | getMotionRange(AXIS_TILT, source); in Compose read event.motionEvent |
| Fast strokes are polygons | Only the current point is read | Read the history first, as in section 3 |
| Two devices mix up each other’s strokes | Pointer IDs belong to a device | Key by (deviceId, pointerId) |
The map
| Topic | Code | Where |
|---|---|---|
| The event | actions, flags, axes, history | MotionEvent.java, reference |
| Pointer IDs | MultiTouchInputMapper::syncTouch() |
MultiTouchInputMapper.cpp |
| Order, actions, cancel | TouchInputMapper::dispatchTouches(), dispatchMotion() |
TouchInputMapper.cpp |
| Touch state per device | TouchState |
TouchState.h, InputDispatcher.cpp |
| Limits | MAX_POINTERS (16), MAX_POINTER_ID (31) |
Input.h |
| Compose types | PointerInputChange, HistoricalChange, PointerType |
PointerEvent.kt |
Compose from MotionEvent |
MotionEventAdapter.convertToPointerInputEvent(), PointerEvent.motionEvent |
MotionEventAdapter.android.kt, PointerEvent.android.kt |
| Compose cancel | sendMotionEvent(), onCancelPointerInput() |
AndroidComposeView.android.kt, SuspendingPointerInputFilter.kt |
Edge cases
- A POINTER_UP still lists the pointer that left. The
MOVEthat follows doesn’t. Read the departing pointer’s last values from the up event. - A MOVE can arrive with no movement. When the same pointers are down as before, the mapper sends a
MOVEwithout checking positions. Don’t assume a move moved. - Limits. An event holds up to 16 pointers (
MAX_POINTERS), with IDs from 0 to 31 (MAX_POINTER_ID). - Events can be split between windows. The dispatcher has
MotionEvent::splitFrom(), which builds an event from a subset of another one’s pointers, chosen by ID, so the index you see in your window need not be the index in the system’s list. Another reason not to key by index. ACTION_OUTSIDE. A touch outside your view’s bounds arrives with only its first location; the reference says to handle it in the root view or the window callback.- Hover ends when touch starts. A pen going down sends
HOVER_EXITfirst. - Don’t keep the event. Compose’s documentation says the framework may recycle the
MotionEventand that holding one is unsafe; copy the numbers you need. - Per-device IDs. A view that takes both a stylus digitizer and a touchscreen sees two streams, each with its own pointer 0.
Cross questions
Two fingers are drawing and the first one lifts. Your code stored strokes in an array by pointer index. What happens to the second stroke?
Its pointer moved from index 1 to index 0, so its next points go to the first slot, which you just removed (the points vanish) or which still holds the first finger's stroke (they land in the wrong one). The ID did not change. That is the whole reason to key by getPointerId().
Does an ACTION_POINTER_UP event still contain the pointer that is going up?
Yes. In dispatchTouches() the pointer is removed only after its up event has been sent, so that event lists it at its last position, and getActionIndex() points at it. The next MOVE no longer does.
A finger lifts and another lands at the same moment. Can the new one get the lifted finger's ID?
Not in that sample, in the code above: new IDs are taken from the set that was in use at the start of the sample, and the set is replaced only after the pass. In the next sample the ID is free again and the lowest free ID goes to the next new finger.
event.x only gives one finger. Which one?
The one at index 0, "regardless of the pointer identifier". It is the first pointer in this event, not the first finger that went down. Loop over pointerCount and use getX(i).
What is the difference between ACTION_UP and ACTION_CANCEL for a stroke?
UP means the user lifted the finger: commit the stroke. CANCEL means the gesture was aborted, so nothing should happen as a result of it: drop the stroke. A cancelled single pointer while others stay down is ACTION_POINTER_UP with FLAG_CANCELED.
Can you compare Compose's change.id.value with MotionEvent.getPointerId()?
No. MotionEventAdapter assigns each new pointer its own ID from a counter and keeps a map from the MotionEvent's ID. The two have no relationship to each other, and Compose's IDs are not reused.
You need tilt in a Compose drawing app. Where does it come from?
PointerInputChange has no tilt, and its historical samples carry only time and position. Use PointerEvent.motionEvent (a read-only, short-lived reference) and read AXIS_TILT. Don't match the change to a pointer by index: Compose orders changes by its own IDs, in order of arrival, while Android orders pointers by its lowest-free IDs, so the two lists can differ even when they are the same size. Find the stylus pointer by tool type in both.
Revision: key points
- A
MotionEventis every pointer at one moment, plus an action; a move also carries history. getActionMasked()gives the action;getActionIndex()gives the pointer for pointer-down and pointer-up.- Index is a place in this event; ID is the finger while it is down. Key by ID.
- The system gives new contacts the lowest free ID and lists pointers in ID order, so indexes shift.
- IDs belong to a device, and are reused after a pointer goes up.
- Read history first, then current values, for every pointer.
getAxisValue()returns 0 for an axis the device doesn’t have: checkgetMotionRange().- Hover goes to
onGenericMotionEvent(). - Cancel is
ACTION_CANCELorACTION_POINTER_UPwithFLAG_CANCELED(API 33): don’t commit. - Compose has its own IDs and only time and position in history; use
motionEventfor the rest.
Cheat sheet
Each concept in a few words.
| Concept | In a few words |
|---|---|
MotionEvent |
Every pointer at one moment, plus an action. |
getActionMasked() |
The action, without the pointer bits. |
getActionIndex() |
Which pointer a pointer-down or pointer-up is about. |
| Pointer index | A place in this event; it can change. |
| Pointer ID | The finger while it is down; key by it. Reused after up. |
| History | Earlier samples inside a MOVE; read them before the current one. |
| Axis | One measured value (pressure, size, tilt); 0 if the device lacks it. |
| Tool type | Finger, stylus, eraser or mouse. |
| Hover | A pen near the glass; arrives in onGenericMotionEvent(). |
| Cancel | ACTION_CANCEL or FLAG_CANCELED (API 33): drop it, don’t commit. |
Compose id |
Compose’s own pointer ID, not the MotionEvent one. |
Read next
- References:
MotionEvent,InputDevice,PointerInputChange,PointerEvent - The web’s counterpart:
PointerEventand Pointer Events, level 3 - The source, in The map above
Search terms that find more: MotionEvent getActionIndex, getPointerId findPointerIndex, ACTION_POINTER_UP FLAG_CANCELED, PointerInputChange motionEvent, getMotionRange AXIS_TILT.
The fine print
Excerpts are from AOSP main and AndroidX androidx-main in November 2026. API levels are from the
Android reference. The order of pointers in an event is undefined in the documentation; what is
described here (lowest free ID, listed by ID, ups then move then downs) is what the touchscreen
mapper does today, and is shown to explain the documentation, not as a promise. Devices that report
through other paths, such as touchpads and some stylus drivers, do not all follow it. The statements
about Compose come from the four files named in The map: I found no handling of FLAG_CANCELED in
them, which is not proof that none exists elsewhere. The pointer table is a model of one touchscreen,
and the pointer pad shows the browser’s API, which differs from Android’s.
Part of the ink series: 1. Why naive drawing feels bad, 2. Canvas, Paint and Path, 3. Looper, epoll and vsync, 4. From glass to your app.