Kai
Kai

Reputation: 51

How to make an android imagebutton object switch images

I am building a board game for the Android platform.

The game has a main screen with a row of buttons that the user uses to indicate how they want to play the game (1 player, 2 player, wi-fi, and network).

I would like the know the most effective way of displaying that a selection was chosen by switching images. I am currently using ImageButton objects to display these options. When the user selects a mode by clicking on it, the image that was there should be replaced by one that is darker. I know how to do this using android:state_pressed so that for the duration of the click, another image shows. However what I need is for the other image to replace the original once the button is clicked, not just while the click is held, until another button is clicked, at which point the button should revert to displaying the first image again. Can someone tell me how to do this please?

Upvotes: 0

Views: 3953

Answers (4)

Cataroux
Cataroux

Reputation: 147

   ImageButton = image;
    int isClicked =  0;

image = (ImageButton) findViewById(R.id.image);
image.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        if (isClicked1 == 0) {
             image.setImageResource(R.drawable.second_image);
            isClicked1 = 1;
        } else {
            image.setImageResource(R.drawable.original_image);
            isClicked1 = 0;
        }

    }
 });

Do you need to know how to set the xml?

Upvotes: 1

JOG
JOG

Reputation: 5640

I would not recommend you to change the background resource. That would differ for each image.

If Alex Orlov's answer does not work out for you, I would try using a State List selector with background drawables defined for android:state_focused and then experiment with these:

image.setFocusable(true);
image.setFocusableInTouchMode(true);
image.requestFocus();

Upvotes: 0

FoamyGuy
FoamyGuy

Reputation: 46846

I agree this seems more like radio button functionality than normal button but you could still accomplish it with an Image button by calling yourButton.setBackgroundResource(R.id.btn_selected) inside your click listener. You'd also have to set which ever button was previously selected back to normal inside the listener.

Upvotes: 1

Alex Orlov
Alex Orlov

Reputation: 18107

There are other states, not just android:state_pressed.

You can use android:state_selected="true" and do urBtn.setSelected(true) on click, and urBtn.setSelected(false) on other button click.

Upvotes: 4

Related Questions