简体   繁体   中英

Android - change image of ImageButton when pressed and release

I would like to set image1 for the button, but when it is pressed - change it to image2. After releasing, the button should be again an image1. I tried to do it this way in onClick() method:

  button.setImageResource(R.drawable.image1);
       if(button.isPressed())
            button.setImageResource(R.drawable.image2);

but after first pressing the image of button changed to the image2 and stayed like that.
Could You help me with that problem?

I think this is what you want:

MyCustomTouchListener myCustomTouchListener = new MyCustomTouchListener();
button.setOnTouchListener(myCustomTouchListener);

Now the MyCustomTouchListener :

class MyCustomTouchListener implement OnTouchListener {
    public boolean onTouch(View v, MotionEvent event)
    {
        switch(event.getAction()){
            case MotionEvent.ACTION_DOWN:
            // touch down code
            button.setImageResource(R.drawable.image1);
            break;

            case MotionEvent.ACTION_MOVE:
            // touch move code
            break;

            case MotionEvent.ACTION_UP:
            // touch up code
            button.setImageResource(R.drawable.image1);
            break;
        }
        return true;
    }
}

您可以使用状态列表drawable轻松地做到这一点,并且不需要任何额外的Java代码(除非您在运行时创建StateListDrawable ,但这比实现自定义触摸交互更合适)。

Use the following:

int dispImg = 0;
button.setImageResource(R.drawable.image1);
if (button.isPress()) {
    if (dispImg == 0) {
        button.setImageResource(R.drawable.image2);
        dispImg = 1;
    }
    else if (dispImg == 1) {
        button.setImageResource(R.drawable.image1);
        dispImg = 0;
    }
}

Explanation: dispImg keeps track of the image you're showing. When it is 0, it means that the 1st Image is showing and so, we should switch to the 2nd.

Hope I Helped :D

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