Home Tutorials Hints & Tips

Getting Started in Android Development

Part 20 - The onTouchListener

The onClickListener can be applied to any view. However, when that view is an image button the user will want some indication that the button has been depressed and released. This is not easy to do with the onClickListener. Fortunately, the Android system provides us with an easy to use method that addresses this issue. It is the onTouchListener. In our example, an image button was reused from the last tutorial. A second image was created to represent the button in the down or pressed state as shown below.

The android image button in a pressed state

The associated Java code for the onTouchListener is show below:

imageButton.setOnTouchListener(new View.OnTouchListener() {
   public boolean onTouch(View v, MotionEvent event) {
      if (event.getAction() == MotionEvent.ACTION_DOWN) {
         //place down action code here
      } else if (event.getAction() == MotionEvent.ACTION_UP){
         //place up action code here
      return false;

The key to understanding the action is to look at the motion events. If the action of the event is to press the image button, then the portion of code placed within the if..then stamen for the MotionEvent.ACTION_DOWN is executed. In our example, that code is simply the code that replaces the current button image with the image representing the button in the down state. That code is shown below:


A new event occurs when the button is released. Here the motion event is ACTION_UP. We can use similar code to replace the down image with the original one:


After this tutorial your OnTouchActivity.java file will look similar to the one below:

After this tutorial your activity_ontouch.xml layout file will look similar to the one below:

After this tutorial your ListviewActivity.java file will look similar to the one below:

After this tutorial your Android Manifest file will look similar to the one below:

Download Download Down Image Button

Download Download tutorial set 1

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved