Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

android - ActionBar up navigation recreates parent activity instead of onResume

I'm using the recommended approach for Up Navigation and my code looks like this:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent h = new Intent(ShowDetailsActivity.this, MainActivity.class);
            h.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(h);
            return true;
        default: return super.onOptionsItemSelected(item);
    }
}

Here's the use-case:

  1. I launch my app which is "MainActivity"
  2. I click a button to go to "ShowDetailsActivity"
  3. I click on the UP ActionBar navigation

The issue is after I click on UP, MainActivity hits its onCreate() methods all over again and loses all state instead of starting at the typical onResume() like it would if I just called "finish()" from ShowDetailsActivity. Why? Is this how it always works and this is expected behavior for Android to recreate all activities that are navigated to using the "Up" navigation approach? If I hit the back button I get the expected onResume lifecycle.

This is my solution if an Android "proper" ones doesn't exist:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent upIntent = new Intent(this, MainActivity.class);
            if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                NavUtils.navigateUpTo(this, upIntent);
                finish();
            } else {
                finish();
            }
            return true;
        default: return super.onOptionsItemSelected(item);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add the following to your parent activity in the manifest file

android:launchMode="singleTop"

regarding to this answer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...