Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android imagebutton change programmatically?

Hello I have an imagebutton linearButton which has a background drawable set in the XML. I want to conditionally replace the background within the code, but it never happens!

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

This seems to be ineffective, is there a "reload" function for a imagebuttons that I have to call before they change visually?

like image 363
CQM Avatar asked Feb 05 '26 06:02

CQM


2 Answers

The invalidate() method will force a redraw of any view:

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

See here for reference.

like image 155
pqn Avatar answered Feb 06 '26 19:02

pqn


The "correct" answer should be updated.

setBackgroundDrawable() was deprecated in API 16

setBackground() was added in API 16

A better answer may be:

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

or just:

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

Will work from API level 1-18

like image 43
EGHDK Avatar answered Feb 06 '26 19:02

EGHDK