开发者

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

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开发者_如何学Go: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!


Hope ths will help you

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


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) {
    }


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜