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). I just want it to become "darker" when it is pressed (like iOS buttons do). 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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.