user195678
user195678

Reputation: 545

change button image in android

I want to change the image of a button in my code. I found this can be done in xml:

please check this link

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

Upvotes: 6

Views: 32191

Answers (2)

swiftBoy
swiftBoy

Reputation: 35783

in onClick method you need to change the Button's image, this way..

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

Upvotes: 11

Will Tate
Will Tate

Reputation: 33509

Assuming an ImageButton... You can change the background image in an onClick listener, similar to the following:

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

Upvotes: 4

Related Questions