0
\$\begingroup\$

I am making some game and I want to create activity again after click on some Button.

For example: I have activities A (game) and B (after game menu). I want to go back to activity A after clicking "Play again" in activity B. But I don't want to resume it but to create it again, so it starts from the beginning. Is there any way of doing this?

I am using android studio.

\$\endgroup\$
1
\$\begingroup\$

When you are finished with an Activity you can destroy it. This means that it won't be running in the background. You can then call a new instance of the activity. This avoids creating and running several instances at the same time. I have created some basic code below and annotated it.

Menu

public class MenuActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {...}

    //Method called when button is clicked
    public void PlayAgain(View view){

        /*
        Start activity used to create the new activity
        Calling a new Intent to change from this activity to the GameActivity
        */
        startActivity(new Intent(this, GameActivity.class));
        //Telling this to finish - ending the activity
        this.finish();
    }
}

GameActivity

public class GameActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {...}
    /*
    Method called when criteria is met to end the activity
    eg: time limit or score condition
    */
    public void onGameFinish(){
        //Same as the menu button, changing activities.
        startActivity(new Intent(this, MenuActivity.class));
        //Ending this activity when we are done with it.
        this.finish();
    }
}

Hope this helps - All the best.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.