Search code examples
javaandroidandroid-activityviewdialog

How to display a Dialog inside a View?


I´m new to android-programming and for the first program I was trying to do a simple Pong-Clone. My program is stitched together from different how-to's and the little bit I was able to handle myself.

The baseline: When I press the "play" button it calls my "GameActivity" which sets my "GameView" as its ContentView. Inside the GameView I handle everything from the game, the ball bouncing, the player(s) and the enemy. But my problem is how to get out of it once one player wins.

At first I wanted to simply call a dialog which asks the player if he wants to play again or go back to the menu, but I cant do anything Activity related of course, because I'm in the "GameView". If I try to it always tells me I can't because "non-static methods cannot be referenced from a static context".

So my GameActivity is quite simple:



public class GameActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(new GameView(this));


    }
}

At first I simply to put something like this into my View:

        InfoDialog infoDialog = new InfoDialog();
        infoDialog.show(getSupportFragmentManager(), "infoDialog");

But as I said as far as I understood I can't do that in a View.

TLDR: How can I stop or change the ContentView from my Activity or call a dialog inside that View?

Like I said I'm very new to Android-programming so sorry if the way that I did this is very convoluted.


Solution

  • You can save the context of this activity on the GameView constructor and use it when you need:

    class GameView extends View {
    
        private Context mContext;
    
        //Constructor
        public GameView (Context context) {
            super(context);
            mContext = context
        }
    
        //Can be called inside the view
        public ShowDialog() {
            AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
            alertDialog.setTitle("Alert");
            alertDialog.setMessage("Alert message to be shown");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
            });
            alertDialog.show();
        }
    }