You should be able to invalidate the canvas in your onClick method for each button. Add a few boolean variables to tell the onDraw method what color to draw.
public static boolean isBlue, isRed, isYellow, isGreen;
public class MainActivity extends Activity {
Button bluebutton, redbutton, yellowbutton, greenbutton;
DrawRectangle dr;
Canvas canvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dr = new DrawRectangle(this);
bluebutton = (Button)findViewById(R.id.bluebutton);
redbutton = (Button)findViewById(R.id.redbutton);
yellowbutton = (Button)findViewById(R.id.yellowbutton);
greenbutton = (Button)findViewById(R.id.greenbutton);
boolean blueColor = false;
bluebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
isBlue = true;
isRed = false;
isGreen = false;
isYellow = false;
dr.invalidate();
}
});
}
The update the onDraw method to check to see what color to draw.
//Used for storing rectangles
public static List<Rect> rectangles;
public class DrawRectangle extends View {
public DrawRectangle(Context context){
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Draw previous rectangles
for(int i=0;i<rectangles.size();i++){
canvas.drawRect(rectangles.get(i), paintColor );
}
Rect ourRect = new Rect();
ourRect.set(0, 0, canvas.getWidth()/2, canvas.getHeight()/2);
Paint paintColor = new Paint();
if(MainActivity.isBlue){
paintColor.setColor(Color.BLUE);
}
paintColor.setStyle(Paint.Style.FILL);
//Draw to actual canvas
canvas.drawRect(ourRect, paintColor );
rectangles.add(ourRect)
} }
In order to draw more Rectangles, you should store the previously drawn Rectangles in a Vector and loop through it each time you invalidate the onDraw method.