0

I want to create a ImageButton and set an image as background mantaining original size. So I use this few lines of code find on StackOverflow too:

ImageButton retry = new ImageButton(this); Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.button2); retry.setImageBitmap(image); retry.setMinimumWidth(image.getWidth()); retry.setMinimumHeight(image.getHeight()); 

But unfortunately I obtain following result:

ImageButton

Obviously I don't want the "background button", but only the image. How can I do?

2
  • have you tried retry.setBackgroundResource(image); Commented Jan 8, 2013 at 21:38
  • @Zohaib yes! it is resized... Commented Jan 8, 2013 at 22:04

2 Answers 2

5

It depends on your image but. You can achieve this by writing style to your button.

Firstl you should define your shape for your button in drawables folder(if it doesnt exist dont hesitate to create and define button_shape.xml).

<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/button_pressed" /> <!-- **pressed button pressed is name of image...** --> <item android:state_focused="true" android:drawable="@drawable/button_focused" /> <!-- focused --> <item android:state_hovered="true" android:drawable="@drawable/button_focused" /> <!-- hovered --> <item android:drawable="@drawable/button_normal" /> <!-- default --> </selector> 

After you define your style in style file.

<style name="button_style"> <item name="android:textColor">#ffffff</item> <item name="android:background">@drawable/button_states</item> </style> 

and set style property of Button.

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

1 Comment

Can I use my shape even if I use an ImageView instead of ImageButton and use this method to set background? Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.button2); retry.setImageBitmap(image); retry.setMinimumWidth(image.getWidth()); retry.setMinimumHeight(image.getHeight());
1

set button's background to transparent color or null.

5 Comments

your way it too complicated )
I add: retry.setBackgroundColor(Color.TRANSPARENT); but it has no effect!
this should work. This line retry.setBackgroundColor(Color.TRANSPARENT) replaces default ImageButton's background with transparent one. Only your image left. Show us more code and explain your problem more carefully.
@Leonidos I fix it. But I use an ImageView instead of ImageButton!
I'm glad to here it, but ImageView isn't a button, so you may face some problems if you try to use ImageView as a button... or you may not )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.