0

I am currently working on developing an app with Android. I am new to the game so I could use a little help. I have a page filled with ImageButtons with a few different images. When they get pressed I want the background of the button to go grey and switch back to the original picture when the user is no longer clicking the button.

Thanks for the help!

Zahan Safallwa
  • 3,880
  • 2
  • 25
  • 32

2 Answers2

1

Check this answer. I think this is related to your question.

For your example, you can have a drawable in your drawable folder. Call it anything. I am calling it button_states.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:drawable="@drawable/cancel" /> <!-- This can be your image -->
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@color/grey" /> <!-- This can be the color you want to show when the button is pressed. Define this in colors.xml -->
    <item
        android:state_enabled="true"
        android:drawable="@drawable/cancel" /> <!-- Use the same image here -->
</selector>

Finally add this drawable as background of your ImageButton. Like this:

<ImageButton
        android:id="@+id/imageButtonSelector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_states" />
Community
  • 1
  • 1
Swagata Acharyya
  • 647
  • 4
  • 10
0

You could do something like this:

final ImageButton imgButton = (ImageButton)view.findViewById(R.id.button);
imageButton.setImageResource(R.drawable.imageIdle);

imgButton.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                imageButton.setImageResource(R.drawable.imagePressed);
                return true;
            case MotionEvent.ACTION_UP:
                imageButton.setImageResource(R.drawable.imageIdle);
                return true;
            default:
                return false;
        }
    }
});

Hope it helps!

Pol
  • 306
  • 2
  • 12