Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Click on ActionBar app icon, create new activity instance

I have an ActionBar in my Android app (API Level 14). There is a home button with my app icon. In MainActivity I write a short Text in an EditText View. When I navigate to PreferenceActivity the icon gets an arrow to signal me, I can navigate to home Activity (MainActivity).

  // PreferenceActivity-onCreate
  ActionBar actionBar = getActionBar();
  actionBar.setDisplayHomeAsUpEnabled(true);

I click on that app icon in ActionBar to return to MainActivity

// PreferenceActivity
@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
   switch (item.getItemId()) 
   {
     case android.R.id.home:
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        return true;
     default:
        return super.onOptionsItemSelected(item);
   }
}

Now my MainActivity was created again und the text in EditText is gone. I thought I can keep alive the MainActivity with die Intent.FLAG_ACTIVITY_CLEAR_TOP. I want to have a behaviour like i use my return button on device.

like image 887
Gepro Avatar asked Dec 27 '12 11:12

Gepro


1 Answers

If you want to return to an existing instance of MainActivity, you need to do this:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

Using CLEAR_TOP alone causes a new instance of MainActivity to be created.

like image 84
David Wasser Avatar answered Nov 11 '22 09:11

David Wasser