Android:在运行时更改矩形的颜色 [英] Android: change color of rectangle at runtime

查看:91
本文介绍了Android:在运行时更改矩形的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 LinearLayout 并且有一个自定义视图:

I have a LinearLayout and I have a custom view:

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中,我有:

in MainActiviy I have:

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更改矩形的颜色。但是在其他地方创建了新矩形!你能帮我吗?

After clicking a button I want to change the color of rectangle by calling changeColor. But new rectangle in some other place is created! Can you please help me?

推荐答案

您正在呼叫 drawRect 两次(在使视图无效之前,以及在 onDraw 上)。另外,也无需存储对 Canvas 的引用。

You're calling to drawRect twice (before invalidating the view, and on onDraw). Also, there's no need to store a reference to Canvas.

将所需的颜色保留在变量中,对其进行更改并使视图无效。-

Keep the desired color in a variable, change it and invalidate the view.-

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();
    }
}

这篇关于Android:在运行时更改矩形的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆