我的非常简单的自定义视图有问题。它的目的只是绘制简单的垂直虚线。我想根据其父容器的按下状态更改线条的颜色。我有这个代码:
public class DottedLine extends View {
float density ;
float size;
Paint paint;
public DottedLine(Context context) {
this(context, null, 0);
}
public DottedLine(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DottedLine(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
density = metrics.density;
size = 2 * density; //2dp
paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(size);
paint.setColor(getResources().getColor(R.color.main_kosapp));
paint.setPathEffect(new DashPathEffect(new float[] {size, size}, 0));
}
@Override
protected void onDraw(Canvas canvas) {
float diff = canvas.getHeight()%size;
Path path = new Path();
path.moveTo(canvas.getWidth()/2, diff/2);
path.lineTo(canvas.getWidth() / 2,canvas.getHeight()-diff/2);
if(this.isPressed() || this.isFocused()) {
paint.setColor(getResources().getColor(R.color.light_gray));
} else {
paint.setColor(getResources().getColor(R.color.main_kosapp));
}
canvas.drawPath(path, paint);
}
}
问题是,onDraw
在我按下视图后没有调用该方法。我试图设置duplicateParentState
为true,但它根本没有帮助。仅供参考,在我的布局中,这个视图有两个直接的兄弟姐妹 - textviews - 它们都有用选择器定义的文本颜色,并且适用于这些文本视图。我的视图实现有什么问题?我需要在类中添加什么才能使选择器工作?