Android:在运行时更改矩形的颜色

时间:2013-09-24 19:13:05

标签: android colors runtime

我有一个LinearLayout,我有一个自定义视图:

public class myView extends View  
{
    Rect rects = new Rect(30,30,80,80); 
    Canvas myCanvas;
    @Override
    public void onDraw(Canvas canvas)     
    {
         myCanvas = canvas;
         paint.setColor(Color.RED);
         canvas.drawRect(rects, paint);

    }
    void changeColor()
    {
        paint.setColor(Color.BLUE);
        myCanvas.drawRect(rects, paint);
        myCanvas.invalidate();
    }
}
在MainActiviy中我有:

LinearLayout lv = (LinearLayout) View.inflate(this, R.layout.activity_main, null);
drawView = new myView(this);
lv.addView(drawView); 
setContentView(lv);
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener()
{
        @Override
        public void onClick(View v) {
            drawView.changeColor();
        }  
});

单击按钮后,我想通过调用changeColor来更改矩形的颜色。但是在其他地方创建了新的矩形!你能帮我吗?

1 个答案:

答案 0 :(得分:6)

您要拨打drawRect两次(在使视图无效之前和onDraw上)。此外,无需存储对Canvas的引用。


在变量中保留所需的颜色,更改它并使视图无效.-

public class myView extends View {

    private Color color = Color.RED;

    Rect rects = new Rect(30,30,80,80); 

    @Override
    public void onDraw(Canvas canvas) {
         paint.setColor(color);
         canvas.drawRect(rects, paint);
    }

    void changeColor() {
        color = Color.BLUE
        invalidate();
    }
}