41

我已将 ImageButton 设置为透明的,因此图标与 Android ActionBar 等背景面板相匹配。这看起来不错,就像我想要的那样。

但是,当背景透明时,不会像在操作栏中按下透明按钮时那样看到蓝色高亮。

我可以有一个透明的 ImageButton 并且单击时高亮闪烁吗?

<ImageButton
    android:id="@+id/nextItemButton"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:background="@null"
    android:src="@drawable/ic_media_ff" />
4

4 回答 4

143

我遇到了同样的问题。最后,我得到了一个具有该属性的代码示例:

android:background="?android:selectableItemBackground"

此属性将为任何视图(按钮、图像按钮、文本视图...)提供具有可选突出显示的透明背景,无需更多编码!!!

于 2012-12-13T00:45:48.987 回答
38

您需要做的就是设置适当的背景。如果您希望它在正常状态下透明而在按下状态下呈蓝色。

在目录中创建一个像这样的StateListDrawableres/drawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/my_bluish_color" android:state_pressed="true"/>
    <item android:drawable="@android:color/transparent"/>
</selector>

这样默认背景是透明的。按下时,背景具有您指定的颜色(而不是颜色,您可以在此处使用任何可绘制对象)。

于 2012-10-10T19:48:46.200 回答
9

只是为了补充费尔南德斯的好答案:

如果您希望效果是圆形而不是矩形,请使用:

android:background="?android:selectableItemBackgroundBorderless"    

(*适用于 V21 及更高版本)。

于 2015-12-16T13:59:29.903 回答
2

如果您想以编程方式执行此操作,这是一种解决方案:

创建一个自定义ImageButton类并覆盖drawableStateChange()

public class CustomImageButton extends ImageButton {

    @Override
    protected void drawableStateChanged() {
        Log.d("Button", "isPressed: " + isPressed() );
        if( isPressed() ){
            setBackgroundResource( android.R.color.holo_blue_dark );
        }  else {
            setBackgroundResource( android.R.color.transparent );
        }
        super.drawableStateChanged();

    }

    public CustomImageButton( Context context ) {
        super( context );
    }

    public CustomImageButton( Context context, AttributeSet attrs ) {
        super( context, attrs );
    }

    public CustomImageButton( Context context, AttributeSet attrs, int defStyle ) {
        super( context, attrs, defStyle );
        // TODO Auto-generated constructor stub
    }



}
于 2012-10-10T19:58:11.307 回答