Android Dev: AlertDialog with SurfaceView
I am developing an Android game and I have my SurfaceView rendering the game and I want to make it so when the player loses or wins an AlertDialog pops up and either restarts the level or whatever.
Basically 开发者_如何学PythonI have two questions:
How do I use AlertDialogs with SurfaceViews? Do I have to put it into the layout.xml or does it get coded into the UI part or the game thread part?
Is there a way to "restart" an activity so it doesn't make a new one just starts the current one over with the same "intent" it was given originally?
Thank You!
You can use this.Start();
on any event to restart the thread in your activity that's the answer of your second question.
Or you can use
if(maze.isGameComplete()) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getText(R.string.finished_title));
LayoutInflater inflater = context.getLayoutInflater();
View view = inflater.inflate(R.layout.finish, null);
builder.setView(view);
View closeButton =view.findViewById(R.id.closeGame);
closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View clicked) {
if(clicked.getId() == R.id.closeGame) {
context.finish();
}
}
});
AlertDialog finishDialog = builder.create();
finishDialog.show();
}
You can restart the activity from SurfaceView class but it is a 'dirty' way, it may flicker, it may take too much memory in the process and crash the application
Intent intent = ((Activity) getContext()).getIntent();
getContext().startActivity(intent); //start the same activity again
((Activity) getContext()).finish(); //finish the previous instance
The proper way is to reinitialize the game by writing a method which will reset all required variables, clear old objects from arraylists etc.
It is possible to use alert dialog, however a standard android dialog would look too basic for a nice game, hence it may be better to create just another gaphics object for the dialog and draw it on screen, which can be even animated... using a transparent activity is another possibility which gives more desing freedom.
精彩评论