简体   繁体   English

按下后退按钮时清除包装

[英]clear bundle when back button pressed

I use fragments (ListFragment) in an activity and i save the selected item to restore it when the screen rotates. 我在活动中使用片段(ListFragment),并保存选定的项目以在屏幕旋转时将其还原。

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentListIndex", mCurrentSelectedItemIndex);
    }

When the user clicks on "back" I don't want to save the item selection. 当用户单击“后退”时,我不想保存项目选择。 I need to override the back button and clear the bundle instance passed to my activity. 我需要覆盖后退按钮,并清除传递给我的活动的捆绑包实例。

I don't really know how to get the bundle instance, I've tried to use a global var but when I use it i have a NullPointerException. 我真的不知道如何获取捆绑实例,我尝试使用全局变量,但是当我使用它时,我有一个NullPointerException。

Here is how i do : 这是我的做法:

private Bundle bundle;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        bundle.clear();
    } 

    return super.onKeyDown(keyCode, event);
}

Where can i retrieve the information I want (currentListIndex): in the onCreate() of my activity / onCreateView() of my detail fragment ? 我在哪里可以获取我想要的信息(currentListIndex):我的活动的onCreate()/我的详细信息片段的onCreateView()?

ok I have found the solution. 好的,我找到了解决方案。

In my class that extends ListFragment : 在扩展ListFragment的类中:

// Restore last state for checked position (when screen orientation
        // change or activity resumed)
        if (savedInstanceState != null) {
            mCurrentSelectedItemIndex = savedInstanceState.getInt(
                    "currentListIndex", -1);
        }

In my activity : 在我的活动中:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    AccountBDD accountBdd = application.getAccountBdd();
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        mCurrentSelectedItemIndex = -1;
    }
    return super.onKeyDown(keyCode, event);
}

and it works 它有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM