How to make a button change its image when it is clicked?

1

How can I make a button (button) made with Swing change its image when it is pressed? Or when you mouse over the button?

Example:

Normal button: ========  Button being pressed: = - = - = - =

It's a bit of a silly example, but I guess they understand me

Thanks:)

    
asked by SinXeros 07.04.2017 в 01:38
source

1 answer

2

You can use a selector defining images for both states, when pressed and normal:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btnOn"/>
<item android:state_pressed="false" android:drawable="@drawable/btnOff"/>
</selector>

This selector is stored in the folder /drawable and you send it in your ImageButton through the property android:src :

<ImageButton android:src="@drawable/image_selector" 
... 
/>

Another option is to change the image by pressing the ImageButton , for example assuming having 2 images within /drawable calls btnOff.png and btnOn.png, when detecting whether the button is pressed or not, we determine to change the images by:

imageButton.setImageResource()

Example:

        final ImageButton imageButton = (ImageButton)findViewById(R.id.imageButton);
        imageButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                    imageButton.setImageResource(R.drawable.btnOff);
                    return true;
                }else if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    imageButton.setImageResource(R.drawable.btnOn);
                    return true;
                }

                return false;
            }
        });

Application where both options are shown:

link

    
answered by 07.04.2017 в 01:47