如何模拟在Android的触摸事件?事件、Android

由网友(沉渣)分享简介:如何模拟触摸事件与Android同时赋予X和Y坐标手动?How to simulate a touch event with Android while giving the X and Y coordinates manually?推荐答案瓦伦丁乌鸦的方式工作,如果你已经扩展你的看法,但如果您使用的是事件侦听器...

如何模拟触摸事件与Android同时赋予X和Y坐标手动?

How to simulate a touch event with Android while giving the X and Y coordinates manually?

推荐答案

瓦伦丁乌鸦的方式工作,如果你已经扩展你的看法,但如果您使用的是事件侦听器,使用这样的:

Valentin Rocher's method works if you've extended your view, but if you're using an event listener, use this:

view.setOnTouchListener(new OnTouchListener()
{
    public boolean onTouch(View v, MotionEvent event)
    {
        Toast toast = Toast.makeText(
            getApplicationContext(), 
            "View touched", 
            Toast.LENGTH_LONG
        );
        toast.show();

        return true;
    }
});


// 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);

要得到更多有关MotionEvent对象,这里是一个很好的答案: Android的:如何创建MotionEvent?

For more on obtaining a MotionEvent object, here is an excellent answer: Android: How to create a MotionEvent?

阅读全文

相关推荐

最新文章