Search code examples
javaandroidsurfaceviewlayout-inflater

Adding a layout on top of SurfaceView


At the beginning I set the content view to a new class, which extends SurfaceView (see the example).

RenderView surfaceView = new RenderView();
setContentView(surfaceView);

But I cannot seem to be able to add a layout from xml file, because inflating requires the first layer that I am adding something on to be View and throws me an error, when I try to inflate like I would do a normal way.

So the question is, how to add some layout from .xml file on top of SurfaceView?

This is the important part of the code of RenderView class:

public class RenderView extends SurfaceView implements Runnable {

Context context;
Thread thread = null;

SurfaceHolder holder;
boolean running = false;

public RenderView(Context context) {
    super(context);
    this.context = context;
    holder = getHolder();
}

public void run() {
    while (running) {
        if(!holder.getSurface().isValid()) continue;
        Canvas c = holder.lockCanvas();


        holder.unlockCanvasAndPost(c);
    }
}

Solution

  • Call this method in your Activity:

    http://developer.android.com/reference/android/app/Activity.html#addContentView(android.view.View, android.view.ViewGroup.LayoutParams)

    The View view parameter can be obtained by inflating your XML layout file

    LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    View secondLayerView = LayoutInflater.from(this).inflate(R.layout.my_layout, null, false);
    addContentView(secondLayerView, lp);