ImageButton 在背景颜色覆盖时显示奇怪的行为

ImageButton displays odd behaviour on background color overwrite

在设置 ImageButton 时,我注意到它有一些灰色背景颜色,与 UI 的其余部分不相配。

这是 ImageButton 的代码

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_material"/>

但是当我尝试像这样将背景覆盖为透明时:

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_material"
    android:background="@android:color/transparent"/>

按钮完全失去了形状和填充

有人知道为什么会这样吗?

使用android:background="#000000"

imageButton.setBackgroundDrawable(null);

发生这种情况是因为您将颜色设置为背景,而颜色没有 size/dimension。

您可以使用任何图片作为背景进行检查,视图将采用该图片的大小。 可以说背景图片不支持刻度类型。

只有 src 支持 ImageView 或其他 class 扩展 ImageView 的缩放类型

imageButton 有背景的原因是因为它基本上是一个带有图像而不是文本的按钮。所以根据 android 文档:

ImageButton public class ImageButton extends ImageView

Displays a button with an image (instead of text) that can be pressed or clicked by the user. By default, an ImageButton looks like a regular Button, with the standard button background that changes color during different button states. The image on the surface of the button is defined either by the android:src attribute in the XML element or by the setImageResource(int) method. To remove the standard button background image, define your own background image or set the background color to be transparent. To indicate the different button states (focused, selected, etc.), you can define a different image for each state. E.g., a blue image by default, an orange one for when focused, and a yellow one for when pressed. An easy way to do this is with an XML drawable "selector." For example:

version="1.0" encoding="utf-8"?>  <selector
> xmlns:android="http://schemas.android.com/apk/res/android">
>      <item android:state_pressed="true"
>            android:drawable="@drawable/button_pressed" /> <!-- pressed -->
>      <item android:state_focused="true"
>            android:drawable="@drawable/button_focused" /> <!-- focused -->
>      <item android:drawable="@drawable/button_normal" /> <!-- default -->  </selector> 

将 XML 文件保存在您的项目 res/drawable/ 文件夹中,然后将其作为您的

源的可绘制对象引用

ImageButton (in the android:src attribute). Android will automatically change the image based on the state of the button and the corresponding images defined in the XML. The order of the elements is important because they are evaluated in order. This is why the "normal" button image comes last, because it will only be applied after android:state_pressed and android:state_focused have both evaluated false. See the Buttons guide.

有关更多信息,请查看文档:Image Button