导论
在Android中模拟一个点击事件有三种方式是通过模拟MotionEvent来实现;一种是通过ADB来实现;一种是通过Instrumentation测试框架来实现
第一种:模拟MotionEvent
通用方法如下:
private void setSimulateClick(View view, float x, float y) {
long downTime = SystemClock.uptimeMillis();
final MotionEvent downEvent = MotionEvent.obtain(downTime, downTime,
MotionEvent.ACTION_DOWN, x, y, 0);
downTime += 1000;
final MotionEvent upEvent = MotionEvent.obtain(downTime, downTime,
MotionEvent.ACTION_UP, x, y, 0);
view.onTouchEvent(downEvent);
view.onTouchEvent(upEvent);
downEvent.recycle();
upEvent.recycle();
}
Demo:
package com.xys.simulateevent;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.MotionEvent;
import and