0

How can I prevent the ActionBar back button (we gonna say ABBB) of my SecondActivity to recreate the MainActivitywhen clicked ?

I have a ListView in the MainActivity and it can be edited using the SecondActivity. The problem is that when the user presses the ABBB, the ListView is reset to default...

However, when the user clicks my OK button or presses physical back button, there is not any problem because I'm using finish();

@Override
public void onBackPressed() {
    finish();
}

If I use this code... :

switch (item.getItemId()) {
    case (android.R.id.home):
        finish();
}

...there is the same problem because, I guess, this method is called after "Android's code".

How can I totally override Android ABBB's clicked code to set it to just call finish(); ?

Drarig29
  • 1,902
  • 1
  • 19
  • 42
  • `switch (item.getItemId()) { case (android.R.id.home): finish(); }` Should not behave the same way! can you post more code from both activities? – Kushal Sharma Oct 27 '15 at 19:44

2 Answers2

2

The ideal scenario is, when are you in the SecondActivity (I take it that, this means that you are in Edit mode), and you press the device back button or ABBB, you show a subtle alert to the user saying "do they really want to dismiss the editing", or go ahead and apply the edit done as in the Contacts application.

So that being said, if all you require is to finish() the activity on press of ABBB, the code that you shown above should work fine (though you need to put return true; after finish()). It works for me. Try the below one in your activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed(); // or finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

I put onBackPressed(); because your ABBB with now imitate your device back button.

Henry
  • 17,490
  • 7
  • 63
  • 98
0

Or, you can set your parent activity's launch mode as -

android:launchMode="singleTop"

that will do all without changing anything.

Reference

Community
  • 1
  • 1
Darpan
  • 5,623
  • 3
  • 48
  • 80