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.