[英]Change button color when pressed with a single image
I have a button that is a nine-patch image. 我有一个按钮,它是九个补丁的图像。 I do not want to provide another image for "pressed" state (that is what
StateListDrawable
requires). 我不想为“按下”状态(
StateListDrawable
要求)提供其他图像。 I just want it to become "darker" when it is pressed (like iOS buttons do). 我只希望它在按下时变得“更暗”(就像iOS按钮一样)。 How can I achieve this?
我该如何实现?
Use something like this: 使用这样的东西:
public class MyStateDrawable extends LayerDrawable {
public MyStateDrawable(Drawable[] layers) {
super(layers);
}
@Override
protected boolean onStateChange(int[] states) {
for (int state : states) {
if (state == R.attr.state_activated || state == android.R.attr.state_pressed) {
super.setColorFilter(0x7f000000, Mode.SRC_ATOP);
return true;
} else if(state == -android.R.attr.state_activated || state == -android.R.attr.state_pressed){
super.setColorFilter(0x00000000, Mode.SRC_ATOP);
return true;
}else {
super.setColorFilter(null);
}
}
return super.onStateChange(states);
}
@Override
public boolean isStateful() {
return true;
}
}
And then 接着
StateDrawable state = new MyStateDrawable(new Drawable[]{mDefaultDrawable});
view.setImageDrawable(state);
Hope this will help you :) 希望这个能对您有所帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.