UPGRAYEDD
UPGRAYEDD

Reputation: 435

Button to go BACK in application

I need to code a button to go BACK to the main application activity.

public void onGotoMainActivity(View View)
    {
         Intent intent = new Intent(View.getContext(), MainActivity.class);
         this.startActivity(intent);
    }

The Main activity is already started and has not been destroyed. So I don't think this would be a "new" intent nor should it "start activity"? Shouldn't it merely call the main activity back to focus?

Upvotes: 1

Views: 611

Answers (5)

UPGRAYEDD
UPGRAYEDD

Reputation: 435

This cleared it all up for me.

public void onGotoMainActiviy(View View)
{
    Intent intent = new Intent(View.getContext(), MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    CurrentActivity.this.finish();
}

Thank you everyone for getting me on the right track. The activities' life cycle was defiantly valuable information.

Upvotes: 0

Dhruvisha
Dhruvisha

Reputation: 2530

You can use this also.

Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();

Upvotes: 1

Frank Cheng
Frank Cheng

Reputation: 6186

Do you mean to simulate a back button?

dispatchKeyevent(Keyevent.ACTION_DOWN, Keyevent.BUTTON_BACK);
dispatchKeyevent(Keyevent.ACTION_UP, Keyevent.BUTTON_BACK);

Upvotes: 0

Bill Gary
Bill Gary

Reputation: 3005

just use finish() in the onClick()

or add this if you're more than 1 activity in

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Upvotes: 0

confucius
confucius

Reputation: 13327

you should set FLAG_ACTIVITY_CLEAR_TOP so instead of launching a new instance of the Activity it will clear all Activities on the top of the stack and deliver the intent to (on top now) Activity with a new Intent

public void onGotoMainActivity(View View)
    {
         Intent intent = new Intent(View.getContext(), MainActivity.class);
         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
         this.startActivity(intent);
    }

Upvotes: 1

Related Questions