You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android自定义矩形View的颜色切换方法不生效问题排查求助

问题原因

你的自定义矩形View颜色切换失效的核心问题是:CustomRectangle类的onDraw()方法中硬编码了画笔颜色为绿色,每次View调用postInvalidate()重绘时,都会把swapColor()方法修改后的颜色强行覆盖回绿色,所以点击按钮看不到任何变化。

同时你的初始化方法没有给画笔设置初始颜色,第一次调用swapColor()时获取到的画笔默认颜色不是绿色,也会导致首次切换逻辑异常。

修复步骤

  1. 删除onDraw()方法中rectPaint.setColor(Color.GREEN)这行硬编码赋值代码
  2. 在init()初始化方法中给画笔设置初始绿色,保证首次绘制和首次切换逻辑正常

修改后的完整自定义View代码:

public class CustomRectangle extends View {

    private static final int SQUARE_SIZE = 200;
    private Rect myRect;
    private Paint rectPaint;

    public CustomRectangle(Context context) {
        super(context);
        init(null);
    }

    public CustomRectangle(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public CustomRectangle(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    public CustomRectangle(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs);
    }

    // 初始化方法
    private void init(AttributeSet attrs) {
        myRect = new Rect();
        rectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // 设置画笔初始颜色为绿色
        rectPaint.setColor(Color.GREEN);
    }

    public void swapColor() {
        rectPaint.setColor(rectPaint.getColor() == Color.GREEN ? Color.RED : Color.GREEN);
        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        myRect.left = 50;
        myRect.top = 50;
        myRect.right = myRect.left + SQUARE_SIZE;
        myRect.bottom = myRect.top + SQUARE_SIZE;

        // 直接使用当前画笔设置的颜色绘制,不再硬编码覆盖
        canvas.drawRect(myRect, rectPaint);
    }
}

修改完成后重新运行应用,点击切换按钮即可正常在绿色和红色之间切换矩形颜色。

内容的提问来源于stack exchange,提问作者Laila Campos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:36:01