ImageButton不会突出显示点击透明背景

我已经设置了一个ImageButton是透明的,所以图标匹配像Android的ActionBar一样的背景面板。 这看起来很好,因为我想要的。

但是,当背景是透明的时候,当您按下操作栏中的透明button时,看不到蓝色的高光。

我可以有一个透明的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" /> 

所有你需要做的就是设置适当的背景。 如果你想让它在正常状态下是透明的,在压缩状态下是蓝色的。

res/drawable目录下创build一个像这样的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:background="?android:selectableItemBackground" 

这attibute将给任何视图(button,ImageButton,TextView的… …)的可选高亮透明背景无需更多的编码!

只要加上费尔南德斯好回答:

如果你想要的效果是圆的,而不是矩形使用:

 android:background="?android:selectableItemBackgroundBorderless" 

(*为V21及以上)。

如果你想以编程的方式来做,这是一个解决scheme:

创build一个自定义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 } }