0

I have a mainActivity in which I use my fragment. and I have two activities Activity1 and Activity2. first I go to fragment to Activity2, when I click back button in Activity2, I need to back to fragment page . it means I need to finish my Activity2 and also finish my Activity1 in one click. how can I get this . here is my back press code on Activity2.

  @Override
public boolean onOptionsItemSelected(MenuItem item) {

    // handle arrow click here
    if (item.getItemId() == android.R.id.home) {
        if(fromString.equalsIgnoreCase("Activity2")){
           this.finish();
           Activity1.finish();

        }else if(fromString.equalsIgnoreCase("Activity1"){

            finish(); // close this activity and return to preview activity (if there is any)

        }
    }
    return super.onOptionsItemSelected(item);
}
Anil
  • 1,605
  • 1
  • 14
  • 24
reddu reed
  • 11
  • 5

2 Answers2

0

As far as i am able to understand by your question you want to finish activity1 if you are from activity1 and both activity1 and activity2 if you are from activity2. You can achieve this by two ways :

First way : Replace your code by this code:

  @Override

public boolean onOptionsItemSelected(MenuItem item) {

// handle arrow click here
if (item.getItemId() == android.R.id.home) {
    if(fromString.equalsIgnoreCase("Activity2")){           
       Activity1.finish();  // I have change the sequence of lines by that it will finish Activity1 first then Activity2 in which is residing
       this.finish();

    }else if(fromString.equalsIgnoreCase("Activity1"){

        finish(); // close this activity and return to preview activity (if there is any)

    }
}
return super.onOptionsItemSelected(item);

}

Second Way : you can clear all your back stack activities by this code and lend to your expected Activity or fragment by this code :

Intent gotoexpectIntent = new Intent(yourActivity.this,yourexpectedActivity.class);
gotoexpectIntent .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(gotoexpectIntent );
chandrakant sharma
  • 1,334
  • 9
  • 15
0

it's still unclear what you are asking. but to finish multiple activities on back press you can try startactivityforresult and go on from there.

Arutha
  • 494
  • 5
  • 14
  • my question is i want to finish activity1 when i when i go back to fragmen from activity1 and both activity1 and activity2 when i go back to fragment from activity2 – reddu reed Sep 07 '17 at 09:39