Reputation: 134
I am facing a situation in which- 1.First I have to set the background image of a ImageButton to a default image. 2.Now at runtime based on some condition I have to change the background image of that ImageButton to some other image.
I have tried this but it doesn't work and the background image remains to default image and doesn't change.
btn.invalidateDrawable((Drawable)getResources().getDrawable(R.drawable.info));
btn.setBackgroundDrawable((Drawable)getResources().getDrawable(R.drawable.infonewred));
How can I achieve this goal.
Upvotes: 2
Views: 3962
Reputation: 11
Try the method setImageResource
Ex:
if(someCondition()){
btn.setImageResource(R.drawable.info);
} else {
btn.setImageResource(R.drawable.infonewred);
}
Upvotes: 1
Reputation: 975
in activity file you can write btn.setBackgroundResource(R.drawable.sliderr);
OR
in your xml layout file you can add one extra line to you button xml code android:src="@drawable/sliderr"
Upvotes: 0
Reputation: 535
I know that's old but i got the solution as i'm also was searching for that, the correct answer is to use setImageResource
, so the code will be like that:
btn.invalidateDrawable(getResources().getDrawable(R.drawable.info));
btn.setImageResource(R.drawable.infonewred);
Upvotes: 1
Reputation: 29141
since you haven't provided xml, i am guessing you are providing src to imageButton.. so to change the source of the image , what you are doing is changing the image background which will not be visible since it is the source which will be visible to you.. so to change source..
do this.
btn.setImageDrawable()
rather than..
btn.setBackgroundDrawable()
Upvotes: 1
Reputation: 3479
Just try following code to change at runtime and for default view set background property in layout xml:
if(yourCondition)
btn.setBackgroundResource(R.drawable.infonewred);
Upvotes: 0
Reputation: 5417
I suggest you set the "default" Background directly in your XML-Layout-File via android:background
.
If you have to change the Background in Runtime just use btn.setBackgroundResource(R.drawable.imagename);
Upvotes: 1