How to programmatically trigger the 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);
how automatically perform touch in android programmatically
You should not do that. If you indeed want to "touch" your view programatically, you should wrap whatever happens in your onTouch method in another function(without the MotionEvent parameter) and call that function, when you want to touch your view. Calling the onTouch without a real touch would get you negative stylepoints
@Override
boolean onTouch(View v, MotionEvent me) {
return action(me.getX(),me.getY());
}
boolean action(int x, int y) {
//do some stuff
}
void somewhereelse() {
//Perform touch action
action(0,0);
}
If you really want to 'dispatch' a touch event. You do it like this:
View v;
v.dispatchTouchEvent(MotionEvent.obtain(0,0,MotionEvent.ACTION_DOWN, 100,100,0.5f,5,0,1,1,0,0));
The values are pretty random. Only the deviceId=0 indicates that it is programatically dispatched Touch.
trigger ontouch event programmatically
If you're using an onTouchListener, the onTouch(...) method is public so I guess you could call it.
So when you instantiate the onTouchListener store it as a variable.
OnTouchListener listener = new OnTouchListener() { [[override code etc.]] }
Then just call the onTouch method you've overridden and give it the view and event you want to simulate the touch on.
MotionEvent doesn't have a contractor, but has a factory method called obtain():
MotionEvent myEvent = MotionEvent.obtain(long downTime, long eventTime, int action, float x, float y, int metaState);
Then just pass it to your onTouch:
onTouch(myView, myEvent);
Assuming you've passed the correct values to your event, it won't know the difference.
For more on the MotionEvent and what the parameters mean, go to:
http://developer.android.com/reference/android/view/MotionEvent.html
Thanks!
programmatically execute Touch event in android
I am not sure if it works, but try this:
MotionEvent event = MotionEvent.obtain(downTime, eventTime, action,
x, y, pressure, size,
metaState, xPrecision, yPrecision,
deviceId, edgeFlags);
onTouchEvent(event);
manually trigger touch event
According to W3C
var e = document.createEvent('TouchEvent');
Then, also change
e.initMouseEvent();
to
e.initTouchEvent();
As you've created a touchstart
event.
The W3C link says:
Some user agents implement an initTouchEvent method as part of the TouchEvent interface. When this method is available, scripts can use it to initialize the properties of a TouchEvent object, including its TouchList properties (which can be initialized with values returned from createTouchList). The initTouchEvent method is not yet standardized, but it may appear in some form in a future specification.
So you'll might have to resort to e.initUIEvent('touchstart', true, true);
In addition, the official spec also states that the TouchList
object is optional, and can be created manually using the createTouchList
method. To add a touch to that list, you'll have to call the createTouch
method, where you'll pass all coordinates and such:
6.1 Methods
#createTouch
Creates a Touch object with the specified attributes.
Parameter | Type | Nullable | Optional | Description
view | WindowProxy | ✘ | ✘ |
target | EventTarget | ✘ | ✘ |
identifier| long | ✘ | ✘ |
pageX | long | ✘ | ✘ |
pageY | long | ✘ | ✘ |
screenX | long | ✘ | ✘ |
screenY | long | ✘ | ✘ |
Return type: Touch
#createTouchList
Creates a TouchList object consisting of zero or more Touch objects. Calling this method with no arguments creates a TouchList with no objects in it and length 0 (zero).
Parameter | Type | Nullable | Optional | Description
touches | Touch | ✘ | ✔ |
Return type: TouchList
If that doesn't work, you could try this:
var e = document.createEvent('UIEvent');
e.initUIEvent();
should work, it makes more sense than createEvent('MouseEvent')
at any rate...
But for testing purposes, why not open your chrome console and check Emulate touch events
, plus override user agent to Android 4. (Ctrl+Shift+j > click the gear bottom right corner, and select Overrides, there you'll find all the settings you need)
Since the touch-events have a long way to go, still in terms of their becoming standardized, it turns out the touches
property is not RO (yet?), so you can use this quick-fix (which the OP found and used with the desired result):
var e = document.createEvent('TouchEvent');
e.touches = [{pageX: pageX, pageY: pageY}];
Which, I think (I can't believe it if it weren't the case) is faster than:
e.touches = e.createTouchList(
e.createTouch(window, target, 0, pageX, pageY, screenX, screenY)
);
How to perform onTouch event from code?
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];
Related Topics
Error:(9, 5) Error: Resource Android:Attr/Dialogcornerradius Not Found
Failure [Install_Failed_Invalid_Apk]
How to Dynamically Set Headers in Retrofit (Android)
Android: Adding Static Header to the Top of a Listactivity
Androidstudio - Module Dependencies in Gradle
Offline Mode for Android App Using the Google Maps API
Android Quotes Within an SQL Query String
Java.Lang.Securityexception: !@Too Many Alarms (500) Registered from Pid 10790 Uid 10206
One Onclickhandler for Multiple Buttons
How to Compile a Static Library Using the Android Ndk
How to Get Add to Home Screen Pop Up on Site Open in Mobile Browser
Http Status Code in Android Volley When Error.Networkresponse Is Null
Extended Surfaceview's Ondraw() Method Never Called
How to Iterate Through All Keys of Shared Preferences
How to Schedule Notifications Using Workmanager