I’m new to Android development and I was wondering if there is a way to add a TouchListener (or any event listener) to a button such that it reacts to movement across it’s area. For instance if I have a button in the middle of the screen and I start swiping from the top it should react when my finger reaches the button area.
This is the code I thought would do it
private OnTouchListener tLis = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// Perform Action
Button b = (Button) findViewById(R.id.button1);
b.setText("Touched");
return false;
}
};
Thanks for any help!
Unfortunately no. Touch events are delivered to child views by their parents, and only if the initial touch event (i.e. ACTION_DOWN) is found to be within the bounds of that view. If a view doesn’t see ACTION_DOWN, it won’t see any subsequent touch event for that gesture.
That’s not to say that it isn’t possible, but it requires more work than just setting a listener on the button. You would need to create a custom
ViewGroupthat fills the screen area and can monitor all the touch events it receives, delivering them to the button when they are inside its bounds regardless of whether the initial down event occurred there or not.An alternative option to a custom parent view is to override the
dispatchTouchEvent()method of yourActivityand monitor the touch events there. Same principle though, you would need to manually forward the touch events to the button when you detect the finger is inside its bounds.Forwarding the event would be done by calling the button’s
dispatchTouchEvent()method directly with theMotionEventyou want to pass, possibly massaged a bit to have a different x/y location before you forward it.As always, when dealing with custom touch code in Android, try not to override the return values of the methods you’re working in unless your sure you have to. Those values govern the entire responder chain of touch events in your app.