Prashant Kumar
Prashant Kumar

Reputation: 134

How to change background image of a ImageButton in android

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

Answers (7)

Johanes
Johanes

Reputation: 11

Try the method setImageResource

Ex:

if(someCondition()){
   btn.setImageResource(R.drawable.info);
} else {
   btn.setImageResource(R.drawable.infonewred);
}

Upvotes: 1

Sritam Jagadev
Sritam Jagadev

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

MRefaat
MRefaat

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

Yashwanth Kumar
Yashwanth Kumar

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

mthpvg
mthpvg

Reputation: 3819

Have you tried btn.setBackgroundResource(R.drawable.infonewred).

Upvotes: 4

Balaji Khadake
Balaji Khadake

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

Thommy
Thommy

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

Related Questions