【问题标题】:Up navigation, proper way to handle向上导航,正确处理方式
【发布时间】:2014-07-01 12:58:05
【问题描述】:

我知道有很多关于处理向上导航的问题,但没有一个让我满意。

我有 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 实例怎么办?

所以我问你:这种情况应该如何正确处理?

【问题讨论】:

    标签: android android-activity navigation android-actionbar


    【解决方案1】:

    一个简单的方法是在启动 BookChapterActivity 并使用新的 Intent 启动 BookActivity 后完成()您的 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");
    

    希望对您有所帮助。

    【讨论】:

    • 谢谢,但是如果没有事先完成 BookActivity 并有意启动它,那么完成 BookChapterActivity 怎么样?这种方法有什么缺点吗?
    • 是的,你的堆栈中会有这个活动,这意味着如果你想以正确的方式离开你的应用程序(按下后退或导航按钮),你必须浏览这个活动两次
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    相关资源
    最近更新 更多