Draw SurfaceView from xml layout

for SurfaceView, which I made from code, I could override onDraw() .
But how to override this onDraw() from SurfaceView , which is defined in the XML layout? is there any way to access draw() method?

+7
source share
1 answer

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!

+28
source

All Articles