android - 按下状态未填充到我的自定义 View

标签 android android-custom-view android-selector

我的非常简单的自定义 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/

相关文章:

Android ScrollView 在旋转动画中丢失剪辑

java - 无限滚动图库的文本自定义

android - 使用按钮选择器禁用按钮

android - 在 Android 中制作像按钮一样的玻璃

android - Firebase 值事件监听器不工作

android - 通过 GSON 将 jsonString 转换为列表

android - SQLiteOpenHelper.close() 和 SQLiteDatabase.close() 有什么区别?

android - 如何在 android 的小部件中以编程方式设置辅助进度?

android - 计算位图平铺高度,以便不裁剪最后一项

android - 在 ExpandableListView 中对父项和子项使用自定义选择器