Using PHP pspell Spell Check Functions with a Custom Dictionary
Visualising Website Performance with Flame Graphs
Development Resource Project
Nice n' Easy JQuery Image Rotator
Book Review: How to Implement Design Patterns in PHP
Installing Xdebug for use with Eclipse or Netbeans on Linux

How to Draw Graphics with SurfaceView

Tuesday, 18 December 12, 2:00 pm
Just as with a regular View, the action in SurfaceView happens in the onDraw() method. To get access to this method, we need to create our own subclass of SurfaceView, where we can then override onDraw() and have it do whatever coding goodness we wish.

In your Android project, right-click on the package where you want to put your SurfaceView subclass, and choose New > Class. Enter a suitably descriptive name for your new class, and click the Browse.. button next to the superclass textbox. This brings up a dialog where we can search for our superclass, by typing in the first few letters of its name:



Double-click it when it appears in the search results pane, and the Superclass box will be populated accordingly. Check the Constructors from superclass box in the method stubs section as these are required, plus they are often useful for performing initialisation tasks. We don't want a main() method though, so leave that unchecked, and we don't need to worry about the Inherited abstract methods checkbox - even if it's checked it won't add any code as SurfaceView is not an abstract class.

When you click the Finish button, you'll see the new Java class inside your app's package. Double-click it to open it in the Eclipse editor, and let's add the onDraw() override using the Source menu, which is found in the main menu at the top of the Eclipse window, and also in the context menu you get by right-clicking in the Editor window. Choose the Override/Implement Methods option, and search for the onDraw(Canvas) method signature that you'll find inside the View thingie:



Check the box and click OK to have the method stub added to your Java class. This particular method is called whenever Android needs to update the display of an active View. Thus it is automatically called when the View first appears, or if another app closes revealing it again. However, if your app updates the display, you'll need to tell Android to redraw it by calling invalidate(). If you're changing the display very often, for instance in a game, you may well find yourself calling invalidate() on every frame.

Please enter your comment in the box below. Comments will be moderated before going live. Thanks for your feedback!

Cancel Post

/xkcd/ Repair Video