Android – Handling touch events – making your buttons more responsive

everyone knows about handling events via onClick.

onClick works fine and all but it’s a little slow. The event doesn’t fire until you’ve actually released (finger or mouse) so you have to first tap and then let go for anything to happen.

What if you want your button to respond immediately after you touch it?

Enter the onTouch event!

You can register onTouch events to any view same as onClick.

Define your listener

public OnTouchListener nextListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				Log.d("base", "next");

			}
			return false;
		}
	};

And then listen for it:

ImageButton nextBtn = (ImageButton) findViewById(R.id.btn_next);
		nextBtn.setOnTouchListener(nextListener);

Notice the if statement above:
if (event.getAction() == MotionEvent.ACTION_DOWN) {
}

We have to do this because when you press a button, you actually receive two touch events from the system. The first touch event is MotionEvent.ACTION_DOWN and as you might imagine the second event is MotionEvent.ACTION_UP

It makes sense that his happens but it took me by surprise at first. I thought there was something wrong with my code when I saw two events coming through on a press.
I only need to worry about when the button is pressed on so I do my stuff when i get the ACTION_DOWN.

Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *