【问题标题】:How do I change a custom View color at runtime?如何在运行时更改自定义视图颜色?
【发布时间】:2014-11-05 20:18:39
【问题描述】:

我的班级定义如下:

public class Island extends View {
    private ShapeDrawable mDrawable;

    public Island(Context context) {
        super(context);
        int width = 50;
        int height = 50;

        mDrawable = new ShapeDrawable(new OvalShape());
        mDrawable.getPaint().setColor(0xff74AC23);
        mDrawable.setBounds(0, 0, width, height);
    }

    public void change() {
        mDrawable.getPaint().setColor(Color.BLACK);
    }

    protected void onDraw(Canvas canvas) {
        mDrawable.draw(canvas);
    }

当我在对象上调用 change() 时,为什么形状不会改变颜色?谢谢。

【问题讨论】:

    标签: android view drawable


    【解决方案1】:

    您需要调用 invalidate 以便视图知道它需要重绘

    【讨论】:

    • 就是这样,谢谢。之前,我试图在可绘制对象本身上调用 invalidateself(),但在视图上调用 invalidate() 效果很好。谢谢。
    【解决方案2】:

    假设你的对象是 , Island island = new Island(context);

    要更新您的视图,您可以调用 island.onDraw() 要么 island.invalidate();

    如果您是从另一个线程更改它,那么您可以使用 postInvalidate() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多