Draw SurfaceView from layout xml

2019-01-19 02:13发布

问题:

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

回答1:

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!