一. MotionEvent.ACTION_SCROLL鼠标滚轮方式

        使用此方式的前提是当前页面支持鼠标滚轮。

        像netflix主页面,只支持上下滚动,左右滚动不支持,他们左右滚动的控件不支持滚动,只支持拖曳,只能使用方式二。

        final MotionEvent.PointerProperties[] pointerProperties = new MotionEvent.PointerProperties[1];
        pointerProperties[0] = new MotionEvent.PointerProperties();
        pointerProperties[0].id = 0;
        final MotionEvent.PointerCoords[] coords = new MotionEvent.PointerCoords[1];
        coords[0] = new MotionEvent.PointerCoords();
        coords[0].setAxisValue(MotionEvent.AXIS_VSCROLL, -2);//底部的内容往上滚动
        //coords[0].setAxisValue(MotionEvent.AXIS_VSCROLL, 2);//顶部的内容往下滚动
        //coords[0].setAxisValue(MotionEvent.AXIS_HSCROLL, -2);//右边的内容往左滚动
        //coords[0].setAxisValue(MotionEvent.AXIS_HSCROLL, 2);//左边的内容往右滚动
        coords[0].x = 960;
        coords[0].y = 540;

        new Thread(new Runnable() {
            @Override
            public void run() {
                Instrumentation instrumentation = new Instrumentation();
                final long time = SystemClock.uptimeMillis();
                instrumentation.sendPointerSync(MotionEvent.obtain(time, time, MotionEvent.ACTION_SCROLL, 1,
                        pointerProperties, coords, 0, 0, 1.0f, 1.0f, 0, 0,
                        InputDevice.SOURCE_CLASS_POINTER, 0));
            }
        }).start();

二. 模拟鼠标拖曳事件

MotionEvent.ACTION_DOWN -> MotionEvent.ACTION_MOVE -> MotionEvent.ACTION_UP
        new Thread(new Runnable() {
            public void run() {
                try {
                    Instrumentation instrumentation = new Instrumentation();
                    long downTime = SystemClock.uptimeMillis();
                    //模拟底部的内容往上滚动。x, y为当前的坐标,可以取屏幕中心点位置。
                    instrumentation.sendPointerSync(MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_DOWN, x, y, 0));
                    instrumentation.sendPointerSync(MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_MOVE, x, y, 0));
                    instrumentation.sendPointerSync(MotionEvent.obtain(downTime, downTime + 20, MotionEvent.ACTION_MOVE, x, y - 100, 0));
                    instrumentation.sendPointerSync(MotionEvent.obtain(downTime, downTime + 30, MotionEvent.ACTION_MOVE, x, y - 200, 0));
                    instrumentation.sendPointerSync(MotionEvent.obtain(downTime, downTime + 40, MotionEvent.ACTION_MOVE, x, 0, 0));//底部y坐标为0,最后移动到此处,上面的down事件才不会响应
                    instrumentation.sendPointerSync(MotionEvent.obtain(downTime, downTime + 60, MotionEvent.ACTION_UP,   x, 0, 0));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐