implement android:src="@drawable/image" programmatically in Android

user788511 picture user788511 · Sep 8, 2011 · Viewed 72.2k times · Source

I am trying to set the foreground image on an image button. After some research, I came across this code sample:

<ImageButton android:text="Button" android:id="@+id/button1"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    android:src="@drawable/icon"/>

My query is how to actually implement android:src in code.

Answer

Marco picture Marco · Sep 8, 2011

Try this:

ImageButton btn = (ImageButton)findViewById(R.id.button1);
btn.setImageResource(R.drawable.newimage);

where newimage is the image name in drawable folder.

EDITED
try this:

ImageButton btn = (ImageButton)findViewById(R.id.button1);
btn.setImageBitmap(bm);

where bm is bitmap extracted from server.

EDITED AGAIN
I see you receive a Drawable; well, do this:

normalImage = Drawable.createFromStream(code);
Bitmap bm = ((BitmapDrawable)normalImage).getBitmap();
ImageButton btn = (ImageButton)findViewById(R.id.button1);
btn.setImageBitmap(bm);