Android: change color of rectangle at runtime

帅比萌擦擦* 提交于 2020-06-27 00:44:33

问题


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

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/18990072/android-change-color-of-rectangle-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!