本文介绍了如何执行从code onTouch事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 myObject.performClick()
我可以模拟从code click事件。
对于是否 onTouch
事件这样的事情存在吗?我可以模仿触摸操作从Java code?
修改
这是我的 onTouch
监听器。
myObject.setOnTouchListener(新View.OnTouchListener(){
@覆盖
公共布尔onTouch(查看视图,MotionEvent motionEvent){
// 做一点事
返回false;
}
});
解决方案
这应该工作,发现这里:How在Android中模拟触摸事件:
//获取MotionEvent对象
长时间的停机= SystemClock.uptimeMillis();
长EVENTTIME = SystemClock.uptimeMillis()+ 100;
浮动X = 0.0;
浮Y = 0.0;
//元状态列表在这里找到:developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
INT亚状态= 0;
MotionEvent motionEvent = MotionEvent.obtain(
停机时间,
EVENTTIME,
MotionEvent.ACTION_UP,
X,
Y,
亚状态
);//调度触摸事件查看
view.dispatchTouchEvent(motionEvent);
有关得到更多有关MotionEvent对象,这里是一个很好的答案:
编辑:并让您的视图的位置,为 X
和是
坐标,使用:
INT [] = COORDS新INT [2];
myView.getLocationOnScreen(COORDS);
INT X = COORDS [0];
INT Y = COORDS [1];
Using myObject.performClick()
I can simulate click event from the code.
Does something like this exist for onTouch
event? Can I mimic touch action from the Java code?
EDIT
This is my onTouch
listener.
myObject.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// do something
return false;
}
});
解决方案
This should work, found here: How to simulate a touch event in Android?:
// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
downTime,
eventTime,
MotionEvent.ACTION_UP,
x,
y,
metaState
);
// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);
For more on obtaining a MotionEvent object, here is an excellent answer: Android: How to create a MotionEvent?
EDIT: and to get the location of your view, for the x
and y
coordinates, use:
int[] coords = new int[2];
myView.getLocationOnScreen(coords);
int x = coords[0];
int y = coords[1];
这篇关于如何执行从code onTouch事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!