You cannot access the onDraw method of a SurfaceView instance declared and added to the layout, like this:
<SurfaceView android:layout_width="fill_parent" android:layout_height="fill_parent" />
The above declaration creates an instance of android.view.SurfaceView and adds it to your layout. You cannot change the behavior of the onDraw method in this instance more than you can change the code / behavior in any other class already compiled.
To achieve what you are asking for, you can create your own subclass of SurfaceView:
package myapp.views; import android.view.SurfaceView; public MySurfaceView extends SurfaceView implements Callback { ... }
And then, to add this to your layout instead of the orignal vanilla SurfaceView, you simply reference the full name of your class as the XML element in your layout:
<myapp.views.MySurfaceView android:layout_width="fill_parent" android:layout_height="fill_parent" />
A SurfaceView subclass must declare a constructor that takes Context and AttributeSet as parameters. And don't forget that your surface view should implement SurfaceHolder.Callback and register itself on the SurfaceHolder:
public MySurfaceView(Context context, AttributeSet attributeSet) { super(context, attributeSet); getHolder().addCallback(this); }
The draw method will not be called automatically, but you can make sure that the initial state of your view is drawn when the surface view is initialized. The callback will be made in surfaceCreated , where you can call the draw-draw method:
public void surfaceCreated(SurfaceHolder holder) { Canvas c = getHolder().lockCanvas(); draw(c); getHolder().unlockCanvasAndPost(c); }
voila!
svjson
source share