实现ActionBar Up按钮

时间:2013-06-03 15:48:43

标签: android android-activity android-actionbar

我正在使用此处发布的方法在ActionBar中实现Up按钮:

ActionBar Up button and Navigation pattern

除了在一个场景中它正常工作:如果活动A创建活动B,然后我按向上它将导航到A没问题。

然而,当我进入活动B,然后我切换到另一个应用程序,然后切换回我的应用程序,现在我按下向上按钮,它将导航我到主屏幕而不是活动A. p>

当我调试时,我可以看到NavUtils.shouldUpRecreateTask(this,upIntent)在两种情况下都返回false,而upIntent确实也是两种情况下的Activity A.所以不确定问题是什么。

@SuppressLint("NewApi")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    if (itemId == 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);
        }
        //finish();
        return true;
    } else if (itemId == R.id.wrap_menu_item) {
        wrapText();
        invalidateOptionsMenu();
        return true;
    } else {
        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:1)

更改活动属性
android:launchMode="singleInstance"

android:launchMode="singleTask"

解决了这个问题。有意义,因为“singleInstance”活动不允许其他任何活动成为其任务的一部分。这是任务中唯一的活动。如果它启动另一个活动,则该活动将分配给另一个任务。因此Up之前工作的唯一原因是因为活动A在前一个活动的“下方”:它给出了它回到之前活动的错觉。