简体   繁体   中英

Android XML ImageView changing Image

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;
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM