4

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;
        }
    });
sandalone
  • 41,141
  • 63
  • 222
  • 338

2 Answers2

18

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];
Community
  • 1
  • 1
stealthjong
  • 10,858
  • 13
  • 45
  • 84
-1

A simple way to perform click motion event

View view;
view.setPressed(true);
view.setPressed(false);
N. Kyalo
  • 47
  • 3