title: How to draw views using Canvas Android?
body: <p>I am trying to draw views dynamically on click of button.On clicking the button,I got an <code>illegal state exception</code> saying; the specified view already has a parent.</p>
  
  <p>Is this the right way to create views dynamically?</p>
  
  <pre><code> @Override
      protected void onCreate(Bundle savedInstanceState)
      {
          super.onCreate(savedInstanceState);
  
  
          draw = new DrawView(this);
  
          relativeLayout = new RelativeLayout(this);
          createButton = new Button(this);
          relativeLayout.addView(createButton);
          setContentView(relativeLayout);
  
          createButton.setOnClickListener(new OnClickListener()
          {
  
              @Override
              public void onClick(View arg0)
              {
                  relativeLayout.addView(draw);
                  setContentView(draw);
              }
          });
  
      }
  
  public class DrawView extends View
  {
      Paint paint;
  
      public DrawView(Context context, AttributeSet attrs)
      {
          super(context, attrs);
      }
  
      public DrawView(Context context)
      {
          super(context);
          paint = new Paint();
      }
  
      @Override
      protected void onDraw(Canvas canvas)
      {
          super.onDraw(canvas);
          paint.setColor(Color.BLACK);
          paint.setStrokeWidth(3);
          canvas.drawRect(30, 30, 80, 80, paint);
          paint.setStrokeWidth(0);
          paint.setColor(Color.CYAN);
          canvas.drawRect(33, 60, 77, 77, paint );
          paint.setColor(Color.YELLOW);
          canvas.drawRect(33, 33, 77, 60, paint );
      }
  }
  </code></pre>