0

I'm trying out some functions and basically learning stuff, and I don't know why this isn't working. I mean when I first touch down the image changes to R.drawable.buttondown, but then when I move my finger or release it the other cases do not work and the image doesn't change anymore. Can you tell me why?

    icon = (ImageView)findViewById(R.id.imageView1);

    icon.setOnTouchListener(new OnTouchListener(){

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                icon.setImageResource(R.drawable.buttondown);
                break;
            case MotionEvent.ACTION_UP:
                icon.setImageResource(R.drawable.ic_launcher);
                break;
            case MotionEvent.ACTION_MOVE:
                icon.setImageResource(R.drawable.abc_ab_bottom_transparent_dark_holo);
                break;
            }
            return false;
    }
Greyshack
  • 1,901
  • 7
  • 29
  • 48

1 Answers1

0

You need to return true to notify android that you have consumed the event.

public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
            icon.setImageResource(R.drawable.buttondown);
            break;
        case MotionEvent.ACTION_UP:
            icon.setImageResource(R.drawable.ic_launcher);
            break;
        case MotionEvent.ACTION_MOVE:
            icon.setImageResource(R.drawable.abc_ab_bottom_transparent_dark_holo);
            break;
        }
        return true;
}

From docs:

True if the listener has consumed the event, false otherwise.

If you return true then you're saying that you just consumed this event and you are interested in the others. If you return false this will hold on the ACTION_DOWN because the event was not consumed.

Pedro Oliveira
  • 20,442
  • 8
  • 55
  • 82
  • Can you explain why? Also I added an empty OnClickListener for that ImageView and it worked as well. Will choose this as best in 3 mins – Greyshack Oct 17 '14 at 15:22
  • if you return false you're telling android that **you do not** consumed the listener. This way the other listener will not be called. If you return true then android will stop processing that ACTION_DOWN event. And therefor it will process the others – Pedro Oliveira Oct 17 '14 at 15:24
  • For a better information check here: http://stackoverflow.com/questions/3756383/what-is-meaning-of-boolean-value-returned-from-an-event-handling-method-in-andro – Pedro Oliveira Oct 17 '14 at 15:26