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

拈花ヽ惹草 提交于 2019-12-09 04:17:30

问题


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.


回答1:


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



回答2:


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!




回答3:


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



回答4:


Hope ths will help you

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



回答5:


One more short variant

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



回答6:


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

imgButton.setImageDrawable(drawable);


来源:https://stackoverflow.com/questions/7346864/implement-androidsrc-drawable-image-programmatically-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!