2013-01-08 311 views
0

我想创建ImageButton并将图像设置为保持原始大小的背景。所以我用代码中找到的StackOverflow上这几行太:为ImageButton背景调整图像大小

ImageButton retry = new ImageButton(this); 

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

但不幸的是我得到以下结果:

ImageButton

很显然,我不希望“背景按钮”,但只图片。我能怎么做?

+0

你有没有试过retry.setBackgroundResource(image); – Zohaib

+0

@Zohaib是的!它是调整大小... –

回答

5

这取决于你的形象,但。您可以通过将风格写入按钮来实现此目的。首先,你应该在你的drawables文件夹中定义你的按钮的形状(如果它不存在,不要犹豫创建并定义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> 

在样式文件中定义样式之后。

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

并设置Button的样式属性。

+0

即使我使用ImageView而不是ImageButton并使用此方法设置背景,我可以使用我的形状吗? 'Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.button2); retry.setImageBitmap(image); retry.setMinimumWidth(image.getWidth()); retry.setMinimumHeight(image.getHeight());' –

1

将按钮的背景设置为透明颜色或为空。

+1

是这是另一种选择和最基本的方式:) – ibrahimyilmaz

+0

你的方式它太复杂了) – Leonidos

+0

是的,但我总是认为没有痛苦没有收益:) – ibrahimyilmaz