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 declaration above creates an instance of android.view.SurfaceView and adds it to your layout. You cannot change the behavior of the onDraw-method on that instance any more than you can change code/behaviour in any other already compiled class.
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 that to your layout instead of the orignal vanilla SurfaceView, you simply refer to the fully qualified name of your class as an XML element in your layout:
<myapp.views.MySurfaceView
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Your 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 to its 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 intial state of your view is drawn when the surface view is initialized. A callback will be made to surfaceCreated
where you can call the draw-method:
public void surfaceCreated(SurfaceHolder holder) {
Canvas c = getHolder().lockCanvas();
draw(c);
getHolder().unlockCanvasAndPost(c);
}
V?ila!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…