Harshit Agarwal
Harshit Agarwal

Reputation: 1345

How to change the Image of the image button dynamically?

I have two set of Images being displayed on ImageButtons and I am changing the images by setting them dynamically. but the new/ changed image is not reflected on screen. I believe it has something to do with refreshing the screen after setting the image. can anyone help me how the image on a imagebutton can be changed dynamically and displayed?

--Thanks in advance

Upvotes: 1

Views: 3447

Answers (5)

Elemental
Elemental

Reputation: 7466

As mentioned by several people using validate or postvalidate works for me in all contexts.

However it sounds as if Android's LevelListDrawable resource is a more appropriate option for you - this allows you to select which image is being displayed from a list of images using a simple SetImagelevel call on the imageview.

Upvotes: 0

Nikhil
Nikhil

Reputation: 16196

Please assign image as "background" image instead of "src" in ImageButton.

Ex:-

<ImageButton android:id="@+id/img1" android:layout_width="wrap_content"
 android:layout_height="wrap_content" android:background="@drawable/btn_yes" />

And In codding side dynamically update as below.

img1.setBackgroundResource(R.drawable.btn_no);

Upvotes: 3

hossaindoula
hossaindoula

Reputation: 980

No need to refresh. From my point of view, like pagination, if you click next button for that button's event handling just replace the drawable resource what you want to put. What I understand from your requirement. Can you be more specific?

Upvotes: 0

Sarmad
Sarmad

Reputation: 389

You can use invalidate() or postInvalidate() depends whether or not you are in UI thread.

Upvotes: 0

Related Questions