使用操作栏主页作为向上按钮,主页活动saveInstanceState始终为null [英] Using actionbar home as up button, home activity saveInstanceState is always null

查看:92
本文介绍了使用操作栏主页作为向上按钮,主页活动saveInstanceState始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

活动A ===单击按钮===>活动B

Activity A ===click button===> Activity B

按下返回按钮时,不会重新创建活动A.

When press back button, Activity A is not recreated.

按下主页按钮作为向上按钮时,将重新创建活动A.

When press home as up button, Activity A is recreated.

所以我在A.onSaveInstanceState(Bundle outState)时保存状态 ,并在A.onRestoreInstanceState(Bundle savedInstanceState)时使用状态.

So I save state when A.onSaveInstanceState(Bundle outState) , and use state when A.onRestoreInstanceState(Bundle savedInstanceState).

保存和使用的效果很好(除了将home作为向上按钮)

Saving and Using works fine (except home as up button)

.

但是,

当按下主页按钮作为向上按钮时, 系统重新创建活动A,并且saveInstanceState消失了.

When pressed home as up button, system recreate Activity A, and savedInstanceState is gone.

如何使用保存实例状态"?

How can I use Saved Instance State?

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
        // I do not want this... 
        // Home as up button is to navigate to Home-Activity not previous acitivity
            super.onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

推荐答案

在onCreate()中启用主页按钮.

In the onCreate() enable the home button.

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
}

在onOptionItemSelected()方法中执行此操作.

In the onOptionItemSelected() method do this.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

这应该启用向上导航.如果您想使用savevedInstanceState还原父活动.您应该在清单文件的父活动中设置launchMode="singleTop".

This should enable Up navigation. If you want the parent activity to be restored with a savedInstanceState. You should set launchMode="singleTop" in the parent activity in Manifest file.

有关更多信息,请查看 http://developer.android.com/:提供导航 a>

For more info check out http://developer.android.com/: Providing Up Navigation

这篇关于使用操作栏主页作为向上按钮,主页活动saveInstanceState始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆