Making a restart button for an Android app game

2020-07-22 18:42发布

I am working on an android app and when I run the main activity the app runs as I want it to but stops after you die in the game. I want to make a restart button appear after you die in the game. So far I've made a new layout with a button and the background of the main activity. I made a new class in my source folder and have set up an onclicklistener but I'm not sure what code will make the the button start the main activity start again.

2条回答
我命由我不由天
2楼-- · 2020-07-22 19:00

You could just call Activity.recreate(); if you're api level is 11 or above.

查看更多
迷人小祖宗
3楼-- · 2020-07-22 19:08

you can add the following code to your onclick method:

finish();
startActivity(getIntent());

by adding the following code, you are restarting the same activity... without going back to the previous one.

UPDATE

here how you can change and restart the game, you need to add flags to start the activity over.

    Intent i = new Intent(this, MainMenu.class); //change it to your main class
    //the following 2 tags are for clearing the backStack and start fresh
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    finish();
    startActivity(i);

try it out, hope it works for you

查看更多
登录 后发表回答