6

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?

Ali Khaki
  • 1,184
  • 1
  • 13
  • 24
user195678
  • 535
  • 4
  • 13
  • 27
  • got it working, sorry for the post. I can check if view == button_name and then use v.setBackgroundResource to achieve the task. – user195678 Feb 08 '11 at 21:18
  • hi.. @user195678 if you got solution for problem then you should either post answer or except any best suitable ans, so all can understand this question is solved and this ans is accepted ... because even i came and posted answer and now read your comments... so please take care of this. – swiftBoy May 30 '12 at 12:25

2 Answers2

11

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);
    }       
}
swiftBoy
  • 35,607
  • 26
  • 136
  • 135
4

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)
            }
        });
Will Tate
  • 33,439
  • 9
  • 77
  • 71