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

前端 未结 6 1062
广开言路
广开言路 2021-02-03 18:24

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



        
相关标签:
6条回答
  • 2021-02-03 19:00

    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);
    
    0 讨论(0)
  • 2021-02-03 19:02

    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!

    0 讨论(0)
  • 2021-02-03 19:16

    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) {
        }
    
    0 讨论(0)
  • 2021-02-03 19:17

    Hope ths will help you

    ImageButton button1=(ImageButton)findViewById(R.id.button1);       
    button1.setImageResource(R.drawable.icon);
    
    0 讨论(0)
  • 2021-02-03 19:18

    One more short variant

    views.setImageViewResource(R.id.button1, R.drawable.newbutton);
    
    0 讨论(0)
  • 2021-02-03 19:19

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

    imgButton.setImageDrawable(drawable);
    
    0 讨论(0)
提交回复
热议问题