How to perform onTouch event from code?

a 夏天 提交于 2019-12-30 07:00:07

问题


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

回答1:


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];



回答2:


A simple way to perform click motion event

View view;
view.setPressed(true);
view.setPressed(false);


来源:https://stackoverflow.com/questions/14098963/how-to-perform-ontouch-event-from-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!