Android imagebutton change programmatically?

╄→尐↘猪︶ㄣ 提交于 2020-01-10 05:26:32

问题


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?


回答1:


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.




回答2:


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




回答3:


Try this one

linearButton.setImageResource(R.drawable.replacementGraphic);

I hope it should work



来源:https://stackoverflow.com/questions/6751875/android-imagebutton-change-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!