ImageButton在透明背景下点击时不会高亮显示

42

我已经设置了一个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个回答

143

我也遇到了同样的问题。最终,我找到了一个带有该属性代码示例:

android:background="?android:selectableItemBackground"

使用该属性,任何视图(按钮、图像按钮、文本视图等)可以在没有更多编码的情况下拥有可选择高亮的透明背景。


3
如果您正在使用ActionBarSherlock,请改用android:background="?selectableItemBackground"。 - NightWhistler
1
这个能否通过编程设置为视图? - Badams
7
好的解决方案,但需要 API 版本 11 或更高:/ - jonathanrz
对于那些想知道的人,这个属性存在于attrs中...就我个人而言,我会使用它的完全限定状态"?android:attr/selectableItemBackground"来保持可读性。 - syklon
1
这应该被选为最佳答案。 - JDJ
显示剩余3条评论

39

你需要做的就是设置正确的背景。如果你希望在正常状态下它是透明的,在按下状态下则是蓝色的。

res/drawable目录中创建一个类似于StateListDrawable的东西。

<?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>

这种方式使默认背景透明。按下按钮时,背景将呈现您指定的颜色(而不是颜色,您可以在此处使用任何可绘制的对象)。


很遗憾,内置的Android样式中的按钮高亮不是公开的。这是我最终选择的自定义颜色。它尽可能接近果冻豆颜色,我认为ICS中的颜色相同:#057891。使用StateListDrawable效果很好。 - Stealth Rabbi
默认的按下颜色取决于设备和 Android 版本。Holo 主题在按下状态下使用半透明蓝色 9-patch drawable。 - Tomik

10

在Fernandez的好回答上补充一点:

如果您想要圆形效果而不是矩形,请使用以下代码:

android:background="?android:selectableItemBackgroundBorderless"    

(*适用于V21及以上版本)。


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
    }



}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接