我的非常简单的自定义 View 有问题。它的目的只是绘制简单的垂直虚线。我想根据其父容器的按下状态更改线条的颜色。我有这段代码:
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);
}
}
问题是,在我按下 View 后,onDraw
方法没有被调用。我试图将 duplicateParentState
设置为 true,但它根本没有帮助。仅供引用,在我的布局中,这个 View 有两个直接的 sibling —— TextView ——它们都有用选择器定义的文本颜色,并且适用于那些 TextView 。
我的 View 实现有什么问题?我需要向类中添加什么才能使选择器正常工作?
最佳答案
您应该通过覆盖 dispatchSetPressed 使您的按下状态 View 无效
@Override
protected void dispatchSetPressed(boolean pressed) {
super.dispatchSetPressed(pressed);
invalidate();
}
至少在不使用 Action 事件的情况下对我有用
关于android - 按下状态未填充到我的自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18936539/