5

I have a problem with touch listener in my android application. OnTouchLIstenr is not working for the view, i.e ACTION_DOWN is performing well in the listener but ACTION_UP doesnt invokes. i dont know whats the problem going on. But if i set the dummy click listener, both working fine. Why is it so?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ImageView image = (ImageView) findViewById(R.id.image);
    image.setOnTouchListener(new OnTouchListener() {            
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView img = (ImageView) v;
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN){
                img.setImageResource(R.drawable.port);
            }else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL){
                img.setImageResource(R.drawable.bar);
            }               
            return false;
        }
    });

}
fargath
  • 7,844
  • 6
  • 24
  • 36

2 Answers2

10

You might consider, returning 'true', since you are handling the touch event.

Link to a similar question. Answer from adamp, makes sense

Community
  • 1
  • 1
varuaa
  • 389
  • 2
  • 9
  • 1
    because you are returning false that mean you are saying to system that "touch is not happened" – Vivek May 26 '11 at 05:18
  • 1
    On ACTION_DOWN event, the listener is called, but he returns a 'false', which means that the listener is saying : "I don't want to handle any further touch events till ACTION_UP. I have added a link, where this is explained. – varuaa May 26 '11 at 05:22
  • 1
    @Hellboy that isn't what the false says! false says I don't want to handle the events, and some other listener below the stack(in case there are multiple views one over the other) can handle. – varuaa May 26 '11 at 05:25
  • Thanks for your good reply guys.. This works fine in the application. – fargath May 26 '11 at 09:13
4
image.setOnTouchListener(new OnTouchListener() {            
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView img = (ImageView) v;
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN){
                img.setImageResource(R.drawable.port);
            }else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL){
                img.setImageResource(R.drawable.bar);
            }               


       return true;
        }
    });

just replace return true; instead of return false; and check

Niranj Patel
  • 32,980
  • 10
  • 97
  • 133