views:

901

answers:

1

HI all,

I'm just getting started with developing for Android. I'm looking to port one of my iPhone applications, but I'm kind of at a loss for how to draw a view at runtime (a view not declared in the XML). Basically, I want to draw a simple rectangle, but then be able to manipulate its frame after being drawn.

Sorry if this is a really, really simple question, but I can't seem to find some equivalent to the iPhone SDK here.

Thanks in advance!

+4  A: 

It sounds like you want to experiment with 2D graphics - for that, you should use a Canvas. You can control the drawing of the Canvas through the invalidate() method, which tells Android to redraw the whole thing triggering your customised onDraw() method. You mention not wanting to use the XML file, but that is the simplest way to put in a Canvas - you don't have to define its contents in the XML file, but simply tell the layout file it's there. A powerful but simple way to put a Canvas in your application is to customise a View. For example, include in your XML file a <your.package.CustomView android:.../> element. Then declare the CustomView extends View class. Any kind of drawing you want to do, put in the onDraw() method.

For example, to draw a rectangle, do something like this.

//First you define a colour for the outline of your rectangle
rectanglePaint = new Paint();
rectanglePaint.setARGB(255, 255, 0, 0);
rectanglePaint.setStrokeWidth(2);
rectanglePaint.setStyle(Style.STROKE);

//Then create yourself a Rectangle
Rect rectangle = new Rect(left, top, right, bottom) //in pixels

//And here's a sample onDraw()
@Override public void onDraw(Canvas canvas){
    rectangle.offset(2, 2);
    canvas.drawRect(rect, rectanglePaint);
}

Every time invalidate() is called from your program, the view will be redrawn and the rectangle moved 2px down and to the right. Note: the redrawing only happens with the main thread is 'waiting'. In other words, if you have a loop calling invalidate several times, the View won't actually be drawn until the loop finishes. You can get around this, but that adds more complication. For an example of how that's done, look at the LunarLander example game from Google - it's a simple game demonstrating a custom View, 2 threads, and how to implement continuous animation.

Steve H
Works beautifully, thank you!
Brian515