Omar Faroque Anik
Omar Faroque Anik

Reputation: 2609

Multiple Rectangle drawing programmatically

enter image description here

I am trying to draw this kind of rectangle but i am unable to do it. I tried to put inside of a loop but id does not show anything. My code snippet is below:

 public class MainActivity extends ActionBarActivity {
    DrawView drawView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    drawView = new DrawView(this);
    drawView.setBackgroundColor(Color.WHITE);
    setContentView(R.layout.activity_main);


    }
 }

DrawView class:

  public class DrawView extends View {
Context context=getContext();
 Paint paint = new Paint();


public DrawView(Context context) {
    super(context);            
}

@Override
public void onDraw(Canvas canvas) {
    int l=50;
    int t=50;
    int r=100;
    int b=100;

    for(int i=0;i<1;i++){
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(3);
        canvas.drawRect(l, t, r, b, paint);
        paint.setColor(Color.WHITE);
        canvas.drawRect(l+3, t+3, r-3, b-3, paint);

        t=t+150;
        b=b+150;
        invalidate(l, t, r, b);
    }

Upvotes: 2

Views: 812

Answers (2)

griffinjm
griffinjm

Reputation: 503

Your version of onDraw() will not work. You call invalidate() in the loop. invalidate() results in a call to onDraw(). So your onDraw() call is effectively recursive.

Upvotes: 1

hasan
hasan

Reputation: 24205

Your DrawView instance is not added to your activity layout.

Try:

setContentView(drawView);

Upvotes: 1

Related Questions