Cornstalks
Cornstalks

Reputation: 38218

Is it possible for my Activity to send generated touch/motion events to its child views?

I have an Activity that generates some MotionEvents (via MotionEvent.obtain()). I'd like to pass these generated touch/motion events to the Activity's children views. From the docs, Activity.onTouchEvent() is only called when one of the child views doesn't handle the event, which means I can't call that to pass the generated touch event to the children.

Is there a way to send a generated touch event from the parent MainActivity to its children views, in such a way that they normally respond (for example, if a child view has an OnClickListener set, and I send a generated down/up touch event to the child view, I'd like the OnClickListener to be called)?

Note that I'm not trying to send touch events from one activity to another, and that this is all in my own application. Also, my devices aren't rooted, so solutions requiring root don't help me.

Upvotes: 1

Views: 253

Answers (1)

Cornstalks
Cornstalks

Reputation: 38218

Just figured it out. The solution is to use Activity.dispatchTouchEvent(). For example, the following registered as a click event on my view:

dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 200, 200, 0));
dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 200, 200, 0));

Upvotes: 1

Related Questions