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.

有帮助吗?

解决方案

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);

其他提示

Here's what worked for me in setting the image:src on an ImageButton programmatically** or through code:

1.Retrieve the image drawable.

Drawable tempImage = getResources().getDrawable(R.drawable.my_image);

2.Get the view.

ImageButton tempButton = (ImageButton)findViewById(R.id.my_image_button);

3.Set the image for the view.

tempButton.setImageDrawable(tempImage);

Hope this works for you too!

try this::

ImageButton tran_btn_skip;

tran_btn_skip = (ImageButton) findViewById(R.id.btn);
    try {
        Bitmap bitmap_skip = BitmapFactory.decodeStream((InputStream) new URL(
                "http://233.129.115.55/MRESC/images/test/skip.png")
                .getContent());
        tran_btn_skip.setImageBitmap(bitmap_skip);
    } catch (Exception e) {
    }

Hope ths will help you

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

One more short variant

views.setImageViewResource(R.id.button1, R.drawable.newbutton);

I know this is an old question, but for future searches... I believe what you are looking for is:

imgButton.setImageDrawable(drawable);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top