Draw SurfaceView from layout xml

26,694

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!

Share:
26,694
Fugogugo
Author by

Fugogugo

Updated on August 05, 2020

Comments

  • Fugogugo
    Fugogugo over 3 years

    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?

  • Fugogugo
    Fugogugo about 13 years
    ok.. how to refer to my class in xml? i don't find a way to do that?
  • svjson
    svjson about 13 years
    Look again at the XML snippet above. The actual XML element is the name of your class. Not very intuitive or XML-ish, that's for sure.
  • Fugogugo
    Fugogugo about 13 years
    I don't understand? does that mean I have to "import" my package name or something??
  • svjson
    svjson about 13 years
    You don't "import" your package name, you simply point out your own implemntation of SurfaceView, which will be instantiated and added to your layout instead of the vanilla SurfaceView. I've edited the answer above to clarify this. I hope that helps.