The solution is to use a StateListDrawable
as the background.
public class ListItemStateListDrawable extends StateListDrawable {
private final int mBackgroundColor, mPressedBackgroundColor, mAngleOffset;
private final Path PATH = new Path();
private final Paint BRUSH_PRESSED = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint BRUSH = new Paint(Paint.ANTI_ALIAS_FLAG);
private boolean isDrawn = false;
private boolean isPressed = false;
public ListItemStateListDrawable(int backgroundColor, int pressedBackgroundColor, int angleOffset) {
this.mBackgroundColor = backgroundColor;
this.mPressedBackgroundColor = pressedBackgroundColor;
this.mAngleOffset = angleOffset;
}
@Override
protected boolean onStateChange(int[] stateSet) {
for(int st : stateSet){
boolean pressed = st == android.R.attr.state_pressed;
boolean not_pressed = st == android.R.attr.stateNotNeeded || st == -android.R.attr.state_pressed ||
st == android.R.attr.state_accelerated || st == android.R.attr.state_focused;
if(pressed || not_pressed){
isPressed = pressed;
invalidateSelf();
break;
}
}
return super.onStateChange(stateSet);
}
@Override
public void draw(Canvas canvas) {
if(!isDrawn){
final int w = canvas.getWidth();
final int h = canvas.getHeight();
PATH.moveTo(0, 0);
PATH.lineTo(mAngleOffset, h * (0.35f));
PATH.lineTo(0, h);
PATH.lineTo(w, h);
PATH.lineTo(w, 0);
PATH.lineTo(0, 0);
PATH.close();
BRUSH.setStyle(Paint.Style.FILL);
BRUSH.setColor(mBackgroundColor);
BRUSH_PRESSED.setStyle(Paint.Style.FILL);
BRUSH_PRESSED.setColor(mPressedBackgroundColor);
canvas.drawPath(PATH, BRUSH);
isDrawn = true;
}else {
canvas.drawPath(PATH, isPressed ? BRUSH_PRESSED : BRUSH);
}
}
}