Change button image in android

I want to change the button image in my code. I found that this can be done in XML:

check this link

but the image will not remain after I released the button. I want to click on the button and change the button to a new image. Can this be done?

+6
source share
2 answers

in the onClick method you need to change the button image in this way.

public void onClick(View v) {
    if(v==buttonName){
        buttonName.setBackgroundResource(R.drawable.imageName);
    }       
}
+11
source

Assuming ImageButton ... you can change the background image in the listener onClickas shown below:

myButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                //set button image
                myButton.setImageBitmap(myBitmapFile)
            }
        });
+4
source

All Articles