1

这是我在 StackOverflow 上的第一篇文章!我有一个后台服务正在运行,我想知道我是否真的可以模拟一个水平的触摸屏手势,而不是仅仅检测到它被调用了。

我可以弄清楚如何捕捉这个事件,但我想实际模拟一个触摸水平手势而不是等待一个。

预先感谢!

4

2 回答 2

3

有一个用于模拟触摸事件 的API 。有些人报告说使用 TouchUtil API 模拟投掷的成功有限。

于 2011-05-02T17:51:02.810 回答
1

模拟 Fling 事件:

/**
 * Simulate touching a specific location and dragging to a new location.
 *
 * @param fromX X coordinate of the initial touch, in screen coordinates
 * @param toX Xcoordinate of the drag destination, in screen coordinates
 * @param fromY X coordinate of the initial touch, in screen coordinates
 * @param toY Y coordinate of the drag destination, in screen coordinates
 * @param stepCount How many move steps to include in the drag
 */
 fun fling(
        fromX: Float, toX: Float, fromY: Float,
        toY: Float, stepCount: Int
    ) {

        val inst = Instrumentation()

        val downTime = SystemClock.uptimeMillis()
        var eventTime = SystemClock.uptimeMillis()

        var y = fromY
        var x = fromX

        val yStep = (toY - fromY) / stepCount
        val xStep = (toX - fromX) / stepCount

        var event = MotionEvent.obtain(
            downTime, eventTime,
            MotionEvent.ACTION_DOWN, fromX, fromY, 0
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            event.source = InputDevice.SOURCE_TOUCHSCREEN
        }
        inst.sendPointerSync(event)



        for (i in 0 until stepCount) {
            y += yStep
            x += xStep
            eventTime = SystemClock.uptimeMillis()
            event = MotionEvent.obtain(
                downTime, eventTime + stepCount,
                MotionEvent.ACTION_MOVE, x, y, 0
            )
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
                event.source = InputDevice.SOURCE_TOUCHSCREEN
            }
            inst.sendPointerSync(event)
        }

        eventTime = SystemClock.uptimeMillis() + stepCount.toLong() + 2
        event = MotionEvent.obtain(
            downTime, eventTime,
            MotionEvent.ACTION_UP, toX, toY, 0
        )

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            event.source = InputDevice.SOURCE_TOUCHSCREEN
        }
        inst.sendPointerSync(event)
    }

用法

 fab.setOnClickListener { view ->
            Thread(Runnable {
                try {

                    fling(500f ,900f ,530f ,20f, 5);
                   // emulateMptionEvent()

                } catch (e: Exception) {
                }
            }).start()
        }
于 2019-10-30T11:35:58.327 回答