开发者

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 b开发者_如何学编程e ineffective, is there a "reload" function for a imagebuttons that I have to call before they change visually?


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.


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


Try this one

linearButton.setImageResource(R.drawable.replacementGraphic);

I hope it should work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜