我有一个使用TintSelectorImageButton
应用色调的视图类DrawCompat::setTintList
:
public class TintSelectorImageButton extends ImageButton{
// Actual resource values seem to be fairly large and positive, so -1 should be a safe sentinel
protected static final int NO_TINT = -1;
public TintSelectorImageButton(Context context, AttributeSet attrs){
super(context, attrs);
TypedArray args = context.obtainStyledAttributes(attrs, R.styleable.TintSelectorImageButton);
if(args.hasValue(R.styleable.TintSelectorImageButton_tintList)){
int colorStates = args.getResourceId(R.styleable.TintSelectorImageButton_tintList, NO_TINT);
if(colorStates != NO_TINT){
ColorStateList colorStateRes = ContextCompat.getColorStateList(context, colorStates);
Drawable wrappedDrawable = DrawableCompat.wrap(getDrawable().mutate());
DrawableCompat.setTintList(wrappedDrawable, colorStateRes);
setImageDrawable(wrappedDrawable);
}
}
args.recycle();
}
}
我通过定义的xml属性为它提供ColorStateList
,如下所示:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:color="@color/sheet_toolbar_disabled"
android:state_enabled="false"/>
<item
android:color="@color/sheet_nav_clicked"
android:state_pressed="true"/>
<item
android:color="@color/sheet_toolbar_enabled"/>
</selector>
不幸的是,当我触摸按钮时,按下的状态实际上并没有显示,但点击事件正在正确传递到提供的View.OnClickListener
:
mPrevSheetButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
showSheet(mPrevSheetUid);
}
});
为了让事情发挥作用,我只是拍摄了图像并在图像编辑器中着色并使用了这个选择器:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/button_prev_light_blue"
android:state_pressed="true"/>
<item
android:drawable="@drawable/button_prev_disabled"
android:state_enabled="false"/>
<item
android:drawable="@drawable/button_prev"/>
</selector>
奇怪的是,可绘制选择器没有问题地达到“按下”状态。
答案 0 :(得分:0)
要使用ColorStateList
将ImageButton
的背景更改为?android:attr/selectableItemBackground
或?android:attr/selectableItemBackgroundBorderless
,
例如,
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackgroundBorderless"
android:src="@drawable/button" />