模拟滚动的实现方式
Android 提供了集中实现模拟滚动的方式:
Instrumentation
的sendPointerSync()
InputManager
的injectInputEvent()
AccessibilityService
的dispatchGesture()
方法
这篇文章主要是介绍如何利用InputManager
来实现模拟滚动,先看一下效果图:
具体实现
由于injectInputEvent
是@hide
的,所以需要使用反射调用此方法。
public class SwipeEvent {
/**
* @param fromX 起始x坐标
* @param fromY 起始y坐标
* @param toX 结束x坐标
* @param toY 结束y坐标
* @param step 单次滑动长度
*/
public void makeSwipeDown(int fromX, int fromY, int toX, int toY, int step) {
InputManager inputManager = (InputManager) getSystemService(Context.INPUT_SERVICE);
int y = fromY;
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis();
// 模拟down
MotionEvent motionEvent = null;
motionEvent = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, fromX, fromY, 0);
// 将MotionEvent的输入源设置为InputDevice.SOURCE_TOUCHSCREEN,输入源为触摸屏幕
motionEvent.setSource(InputDevic