views:

327

answers:

3

Creating a game in Android using multiple Buttons to display an image from the drawable folder. I want to change the button to a different image after the button has been clicked on. Here is the button code:

    <Button android:id="@+id/b36"
    android:background="@drawable/black"
    android:layout_width="45px"
    android:layout_height="45px"
    />  

I can't find anything about how to change the actual image of the button. You can change the color of the button by using the following code in the java file:

b36.setBackgroundColor(0xAA00AA00);
+1  A: 

Maybe you want to use an ImageButton. Then you can call methods like button.setImageDrawable() and such.

synic
+2  A: 

you have to use image view as button. set the image view's background to a xml file. in resource drawable we can use xml files. check the Api demos drawable folder. that xml file contains this code.

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"&gt;

<item android:state_pressed="false"
    android:drawable="@drawable/button _image_in_normal_state" />

<item android:state_pressed="true"
    android:drawable="@drawable/button _image_in_pressed_state" />

</selector>

and put those to image files in res/drawable folder. you can achieve what you want?

also refer this link

Praveen Chandrasekaran
This helped me out a lot, but as it turns out you can use this for most views including Button as it is. you just set the image background to this resource file. Great answer
mtmurdock
A: 

Quick example for changing the background of a button once pressed.

In the oncreate of your activity:

   btn_36= (Button) findViewById(R.id.b36);
   btn_36.setOnClickListener(new OnClickListener() {
       public void onClick(View v) {
           btn_36.setBackgroundResource(R.drawable.white);
       }
   });
stealthcopter