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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With