Changing the image in a button after clicking?

Creating a game on Android with a few buttons to display an image from a drop down folder. I want to change the button to a different image after the button is clicked. Here is the code for the button:

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

      

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

b36.setBackgroundColor(0xAA00AA00);

      

+2


a source to share


3 answers


you need to use the image as a button. set image background to xml file. xml files can be used in the resource. check the Apo demos drawable folder. this XML file contains this code.

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

<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 place them in image files under res / drawable folder. can you achieve what you want?

also link to this link

+3


a source


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

, etc.



+1


a source


A quick example of changing the background of a button after clicking.

In 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);
       }
   });

      

0


a source







All Articles