title: Canvas (onDraw) Android
body: <p>I have been trying to draw different rectangles on the canvas after several times of button click. It should display different colored rectangle and the rectangle should remain on canvas after every button click. The rectangles should be able to move around the canvas. I have written the View class but i have no idea how to implement the onDraw() method on activity after a button click and also no idea of ways to create different color of rectangle.</p>
  
  <p>I have 4 buttons on my main.xml file. </p>
  
  <pre><code>public class DrawRectangle extends View {
  
  public DrawRectangle(Context context){
  
      super(context);
  
  }
  
  @Override
  protected void onDraw(Canvas canvas) {
      // TODO Auto-generated method stub
      super.onDraw(canvas);
  
      Rect ourRect = new Rect();
  
      ourRect.set(0, 0, canvas.getWidth()/2, canvas.getHeight()/2);
  
      Paint blue = new Paint();
  
      blue.setColor(Color.BLUE);
  
      blue.setStyle(Paint.Style.FILL);
  
      //Draw to actual canvas
      canvas.drawRect(ourRect, blue);
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p>This is my activity class.</p>
  
  <pre><code>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);
  
  
  
  bluebutton.setOnClickListener(new View.OnClickListener() {
  
      @Override
      public void onClick(View arg0) {
          // TODO Auto-generated method stub
  
                  dr.onDraw();
      }
  });
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Do i have to implement the onTouchListener as well so that the rectangles can move around?</p>
  
  <p>Please advice. Thank you.</p>