开发者

Draw SurfaceView from layout xml

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 dra开发者_如何学运维w() method?


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜