6

I'm downloading the image from server and storing it in bitmap object. I want to set this image as background for button. But the button doesn't have the property setImageBitmap. So is there anyway I can set the background of button with the downloaded bitmap image? Like by converting the bitmap to drawable? Sorry, I'm new to Android, please bear with my mistakes (if any).

P.S : I want to use button control only. Because I want some text at the bottom of each buttons and I'm creating these buttons dynamically.

2

4 Answers 4

19

The best way to convert a Bitmap to drawable in android is as follows,

Drawable drawable = new BitmapDrawable(getResources(), bitmap); 

where bitmap is the name the Bitmap. Then set the drawable as your Button background as follows,

btn.setBackground(drawable);

N.B: Without specifying getResources() as the first argument, you may experience inconsistent image sizing across different screen densities.

for more info refer this http://developer.android.com/reference/android/graphics/drawable/BitmapDrawable.html

Sign up to request clarification or add additional context in comments.

Comments

1

Simply use BitmapDrawable.

Drawable drawable=new BitmapDrawable(contact_pic); 

Comments

1

Convert Bitmap to BitmapDrawable like this

Drawable drawable = new BitmapDrawable(getResources(),your_bitmap);

and then set it as background to button as ,

button.setBackgroundDrawable(drawable);

P.S. You can also do the same inline as ,

button.setBackgroundDrawable(new BitmapDrawable(getResources(),your_bitmap));

Comments

1

This is how to do it, I've used several times:

Drawable drawable = (Drawable)new BitmapDrawable(Bitmap);    
Button button= new Button(this);    
button.setBackground(drawable); 

2 Comments

setBackground method is only available from API level 16.
How can I use the converted drawable in setCompoundDrawablesWithIntrinsicBounds(int, int, int, int) method? Because it takes all int parametres.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.