Search code examples
androidimagebutton

Set bitmap background on ImageButton in Android


I want to set an Image background at run time on ImageButton. I know I can use the following code:

Bitmap b=bitmap;
ImageButton btn;
btn=(ImageButton)findViewById(R.id.myButton);
btn.setBackground(d);

but the above code requires android API 16, and I am working on lower API. I also know the following code can be used:

ImageButton imgButton = (ImageButton) findViewById(R.id.myButton);
imgButton.setBackgroundResource(R.drawable.myImage);

but with this, I have a problem that the image that I am trying to set is not available in the resources and is generated at run time.

How can I set an image to ImageButton at run time in android with APIs before API level 16.

Thanks


Solution

  • use setBackgroundDrawable(Drawable)...

        Bitmap b = bitmap;
        ImageButton btn;
        btn = (ImageButton) findViewById(R.id.myButton);
        BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), b);
        btn.setBackgroundDrawable(bitmapDrawable);