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!
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 theinvalidate()
method, which tells Android to redraw the whole thing triggering your customisedonDraw()
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 theCustomView 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.
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.