Search code examples
androideventstouch-event

How to perform onTouch event from code?


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

Solution

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