Skip to content

Instantly share code, notes, and snippets.

@vhart
Created January 12, 2018 17:23
Show Gist options
  • Save vhart/986b388a24703ceb0c33eff67ea935ff to your computer and use it in GitHub Desktop.
Save vhart/986b388a24703ceb0c33eff67ea935ff to your computer and use it in GitHub Desktop.
Multi Touch View Action For Espresso
import android.support.test.espresso.ViewAction
import android.support.test.espresso.ViewInteraction
import android.support.test.espresso.action.CoordinatesProvider
import android.support.test.espresso.UiController
import android.view.InputDevice
import android.view.MotionEvent
import android.os.SystemClock
class MultiTouchDownEvent : ViewAction {
val locations: Array<Pair<Float, Float>>
constructor(locations: Array<Pair<Float, Float>>) {
this.locations = locations
}
override fun getDescription(): String {
return "Multi Touch Event"
}
override fun getConstraints(): Matcher<View> {
return isDisplayed()
}
override fun perform(uiController: UiController, view: View) {
val screenPos = IntArray(2)
view.getLocationOnScreen(screenPos)
val coordinatesList = buildCoordinatesList(screenPos)
val pointerProperties = buildPointerPropertiesList()
println(coordinatesList)
val downTime = SystemClock.uptimeMillis()
val eventTime = SystemClock.uptimeMillis()
for (i in coordinatesList.indices) {
val pointerCount = i + 1
val coordinatesSlice = coordinatesList.subList(0, pointerCount)
val propertiesSlice = pointerProperties.subList(0, pointerCount)
val eventType = pointerDownEventType(pointerCount)
val event = MotionEvent.obtain(downTime,
eventTime,
eventType,
pointerCount,
propertiesSlice.toTypedArray(),
coordinatesSlice.toTypedArray(),
0,
0,
1f,
1f,
0,
0,
InputDevice.SOURCE_UNKNOWN,
0
)
uiController.injectMotionEvent(event)
event.recycle()
}
}
private fun buildCoordinatesList(screenPosition: IntArray): List<MotionEvent.PointerCoords> {
return locations.map {
val coordinate = MotionEvent.PointerCoords()
coordinate.x = it.first + screenPosition[0]
coordinate.y = it.second + screenPosition[1]
coordinate.pressure = 1f
coordinate.size = 1f
coordinate
}
}
private fun buildPointerPropertiesList(): List<MotionEvent.PointerProperties> {
return IntArray(locations.count()) { it }.map {
val pointer = MotionEvent.PointerProperties()
pointer.id = it
pointer
}
}
private fun pointerDownEventType(numberOfPointers: Int): Int {
if (numberOfPointers < 1) return -1
var eventType = if (numberOfPointers == 1) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_POINTER_DOWN
eventType += (numberOfPointers shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)
return eventType
}
}
@zezekalo
Copy link

eventType += (numberOfPointers-1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment