ddavtian
ddavtian

Reputation: 1361

How to detect touch events in Android

Is it possible to detect all touch events in an Activity and capture it and then in return pass that pass event to another View?

For example:

Button 1 and Button 2. When Button 1 is pressed I want to capture that touch/click event and automatically pass that touch event to Button 2, basically with one touch/press you get the click generated and that same click is passed on to the second button automatically.

Upvotes: 10

Views: 18212

Answers (2)

theWook
theWook

Reputation: 843

take look this API description first.


boolean android.app.Activity.dispatchTouchEvent(MotionEvent ev)

public boolean dispatchTouchEvent (MotionEvent ev) Since: API Level 1 Called to process touch screen events. You can override this to intercept all touch screen events before they are dispatched to the window. Be sure to call this implementation for touch screen events that should be handled normally.

Parameters ev The touch screen event.

Returns boolean Return true if this event was consumed.

As you can see, you can intercept all touch events.

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    // TODO Auto-generated method stub
    super.dispatchTouchEvent(ev);
    if(btn1.onTouchEvent(ev)){
        return btn2.onTouchEvent(ev);
    }else{
        return false;
    }
}

These codes are what you are looking I think.

Upvotes: 20

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

I imagine that you could take the TouchEvent from the button press, and make a call to the other button, passing in the TouchEvent, but I am not sure how safe that would be. (Android may bomb on you)

A safer solution would be to subclass Button, and use the Observer design pattern. You could register each buttons to listen for button presses of each other button, and then you would be able to safely pass the TouchEvent's between all of them.

If you are unfamiliar with the Observer design pattern, here is a link: http://en.wikipedia.org/wiki/Observer_pattern

Upvotes: 3

Related Questions