Search code examples
androidsurfaceview2d-games

android game over screen


I have created this little game using SurfaceView and now I want to show the game over screen. Since the SurfaceView's update and render methods are being called by another Thread I want to know how to correctly inflate the game over XML and add it to the screen.

PD: by that I mean that I know I can use a reference to the activity, and I could do

public void render() {
  if(gameOver) {
    View gameOverView = LayoutInflater.from(activity).inflate(R.layout.gameover);
    // code to get the layout
    // and finally 
    layout.addView(gameOverView);
  }

but the thing is that activity was created in the UI thread, and render() is called by a secondary thread, so it throws an exception.


Solution

  • You way should work if you will wrap it in runOnUiThread:

    public void render() {
      if(gameOver)
        activity.runOnUiThread(new Runnable() {
    
        @Override
        public void run() {
            View gameOverView = LayoutInflater.from(activity).inflate(R.layout.gameover);
                // code to get the layout
                // and finally 
                layout.addView(gameOverView);
    
        }
        });
    }
    

    May be better to start another activity for the game over screen?