使用AccessibilityService模拟点击事件的方法:
AccessibilityNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
但是前提是这个AccessibilityNodeInfo具有Onclick能力,也就是isClickable()为true。
问题在于控件的点击效果不一定非得通过onClick方法实现,也可以通过onTouchEvent方法实现。当通过onTouchEvent方法实现的时候,就无法通过AccessibilityNodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK)方法模拟这个控件的点击事件了。
一、点击效果通过onClick方法实现
id_btn_openFloatWindow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.i("onClick", "onClick");
}
});
二、点击效果通过onTouchEvent方法实现
id_btn_openFloatWindow.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
onTouchEvent(event,v);
return true;//改为true,则不会触发OnClick方法
}
});
private boolean onTouchEvent(MotionEvent event, View view) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("onTouchEvent", "ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP:
Log.i("onTouchEvent", "ACTION_UP");
break;
}
return true;
}
如果采用OnTouchEvent方法实现点击事件并且没有做到和辅助功能兼容,那么也就无法通过onTouchEvent模拟该控件的点击事件了。
===================================================================
onTouchEvent方法实现与辅助性服务保持兼容性的解决方案:
- 生成一个接近解释AccessibilityEvent的点击动作。
- 对不能使用触摸屏的用户提供自定义点击动作的辅助性服务。
class CustomTouchView extends View { public CustomTouchView(Context context) {
super(context);
} boolean mDownTouch = false; @Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event); // Listening for the down and up touch events
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownTouch = true;
return true; case MotionEvent.ACTION_UP:
if (mDownTouch) {
mDownTouch = false;
performClick(); // Call this method to handle the response, and
// thereby enable accessibility services to
// perform this action for a user who cannot
// click the touchscreen.
return true;
}
}
return false; // Return false for other touch events
} @Override
public boolean performClick() {
// Calls the super implementation, which generates an AccessibilityEvent
// and calls the onClick() listener on the view, if any
super.performClick(); // Handle the action for the custom click here return true;
}
}
上面所示的模式通过调用performClick()方法确保了自定义点击事件是与辅助性服务兼容的,performClick()方法既生成一个辅助性事件,又提供一个访问辅助性服务的入口,来代表用户执行了自定义的点击事件。
参考资料:
http://www.xuebuyuan.com/2061597.html