Destroying an activity

Pressing the back button will destroy the current activity.

If you don’t want to destroy the activity using the back button, you can also use the finish(); method provided by the Activity class to destroy the current activity.

For example, in the delete menu event listener from our previous lesson.

Give our delete menu the function to exit the current activity.

public boolean onOptionsItemSelected(MenuItem item) {
    // [English] Toast.makeText(FirstActivity.this,"xxx",Toast.LENGTH_SHORT).show();
    switch (item.getItemId()) {
        case R.id.add:
            Toast.makeText(FirstActivity.this,"Add Course",Toast.LENGTH_LONG).show();
            break;
        case R.id.del:
            finish(); // [English] Destroy current activity
            break;
        default:
            Toast.makeText(FirstActivity.this,"Unknown",Toast.LENGTH_LONG).show();
    }
    return super.onOptionsItemSelected(item);
}Code language: JavaScript (javascript)

Exiting the activity: if it is the main activity, the app exits directly; if it is a child activity, it returns to the previous activity.

Destroying an activity

Leave a Reply

Your email address will not be published. Required fields are marked *