Android image changed programmatically?

Hello, I have a button with a linearButton image that has an installed background in XML. I want to conditionally replace the background in the code, but it will never happen!

 Drawable replacer = getResources().getDrawable(R.drawable.replacementGraphic); linearButton.setBackgroundDrawable(replacer); 

This seems ineffective, is there a โ€œreloadโ€ function for buttons with images that I have to call before they change visually?

+3
android xml drawable imagebutton
Jul 19 '11 at 18:05
source share
3 answers

The invalidate() method will force you to redraw any view:

 Drawable replacer = getResources().getDrawable(R.drawable.replacementGraphic); linearButton.setBackgroundDrawable(replacer); linearButton.invalidate(); 

See here for reference.

+7
Jul 19 '11 at 18:54
source share
โ€” -

The "correct" answer must be updated.

setBackgroundDrawable() deprecated in API 16

setBackground() was added in API 16

A better answer might be:

 int replace = R.drawable.my_image; myButton.setBackgroundResource(replace); myButton.invalidate(); 

or simply:

 myButton.setBackgroundResource(R.drawable.my_image); myButton.invalidate(); 

Will work from API level 1-18

+3
Aug 2 '13 at
source share

Try this one

 linearButton.setImageResource(R.drawable.replacementGraphic); 

I hope it should work

0
Oct 18 '13 at 6:35
source share



All Articles