How to execute onTouch event from code?

Using myObject.performClick() , I can simulate a click event from the code.

Does something like this exist for the onTouch event? Can I simulate a touch action from Java code?

EDIT

This is my onTouch .

  myObject.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { // do something return false; } }); 
+4
source share
2 answers

This should work, 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); 

More on getting a MotionEvent object, here is a great answer: Android: how to create a MotionEvent?

EDIT: and to get the location of your view for x and y coordinates use:

 int[] coords = new int[2]; myView.getLocationOnScreen(coords); int x = coords[0]; int y = coords[1]; 
+13
source

A simple way to execute a click event

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

Source: https://habr.com/ru/post/983280/


All Articles