2014-07-01 104 views
0

我知道有很多关于处理Up导航的问题,但他们都不满足我。上导航,正确的方式处理

我有3个活动:MainActivity,BookActivity,BookChaptersActivity。 BookActivity会接收一些额外内容以正确初始化。我使用这个建议的方式来浏览:

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
    // Respond to the action bar's Up/Home button 
    case android.R.id.home: 
     Intent upIntent = NavUtils.getParentActivityIntent(this); 
     if (NavUtils.shouldUpRecreateTask(this, upIntent)) { 
      // This activity is NOT part of this app's task, so create a new task 
      // when navigating up, with a synthesized back stack. 
      TaskStackBuilder.create(this) 
        // Add all of this activity's parents to the back stack 
        .addNextIntentWithParentStack(upIntent) 
        // Navigate up to the closest parent 
        .startActivities(); 
     } else { 
      // This activity is part of this app's task, so simply 
      // navigate up to the logical parent activity. 
      NavUtils.navigateUpTo(this, upIntent); 
     } 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 

但是使用最多的导航里面BookChapterActivity的时候,我又回到了BookActivity,但它被重新演员没有,所以它是完整的混乱。 我知道推荐的方法来解决这个问题是通过使用: android:launchMode =“singleTop” 里面的清单。但是我不认为这是处理这个问题的正确方法。如果我想拥有多个BookActivity实例会怎么样?

所以我问你:这种情况应该怎么处理好?

回答

0

一个简单的方法是在启动BookChapterActivity之后完成()您的BookActivity,并在返回时用新的Intent +您的额外参数启动BookActivity。

BookChapterActivity

@Override 
public boolean onMenuItemSelected(int featureId, MenuItem item) { 

    switch(item.getItemId()) { 
     case android.R.id.home: handleBack();break; //Navigation UP Button was pressed. 
     default: return true; 
    } 
    return true; 
} 

而且这种方法被称为:

private void handleBack() { 
//put your extras in the new intent 
    Intent bookActivity = new Intent(this,BookActivity.class); 
    bookActivity.putExtra("key","extra"); 
    startActivity(bookActivity); 
    finish(); 
} 

BookActivity(接收信息)

Intent getBundleExtras = getIntent(); 
Bundle getBundleExtrasBundle = getBundleExtras.getExtras(); 
String extra = getBundleExtrasBundle.getString("key"); 

希望有所帮助。

+0

谢谢,但是如果完成BookChapterActivity而未事先完成BookActivity并以意向启动它呢?这种方法有什么缺点吗? – connexion20000

+0

是的,你会在你的堆栈中进行这项活动,这意味着如果你想以正确的方式离开你的应用(按下后退或导航按钮),你必须两次浏览这个活动 – Milchkanne