调整ImageButton背景的图像大小

Ste*_*te_ 0 android imagebutton

我想创建一个ImageButton并将图像设置为保持原始大小的背景.所以我在StackOverflow上也使用了几行代码:

ImageButton retry = new ImageButton(this);

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

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

的ImageButton

显然我不想要"背景按钮",而只需要图像.我能怎么做?

ibr*_*maz 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>
Run Code Online (Sandbox Code Playgroud)

在样式文件中定义样式后.

<style name="button_style">
    <item name="android:textColor">#ffffff</item>
    <item name="android:background">@drawable/button_states</item>
</style>
Run Code Online (Sandbox Code Playgroud)

并设置Button的style属性.