I have a custom View
, which overrides onDraw
and basically draws a custom shape with canvas.
I would like to change the color, when the view is touched.
Looking around StackOverflow, it seems like the preferred way for Buttons is to set up a drawable selector list with various colors set on android:state_pressed
and android:state_focused
.
However, that approach does not seem to work for me, as I am drawing the shape myself, and the color is set on my own Paint
object.
Here's what I have now:
I set up custom attributes as such with a simple color attribute:
<declare-styleable name="CustomView">
<attr name="color" format="color"/>
</declare-styleable>
I retrieve the color in CustomView
's constructor, and setup a Paint
:
private final Paint paint;
...
TypedArray conf = context.obtainStyledAttributes(
attributes,
R.styleable.CustomView
);
Resources resources = getResources();
int color = conf.getColor(
R.styleable.CustomView_color,
resources.getColor(R.color.blue)
);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
Finally, I use it in onDraw
:
canvas.drawPath(shapePath, paint);
I started looking into a ColorStateList, but I am unclear on how I would integrate it into my code. Any suggestions on how to achieve the selector list functionality for my custom view would be much appreciated!