还原导航选项卡状态时的IndexOutOfBoundsException

时间:2013-02-14 10:08:10

标签: android

我正在使用操作栏标签导航,当我旋转屏幕时,我得到IndexOutOfBoundsException

根据logcat问题在getSupportActionBar().setSelectedNavigationItem( savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Restore the previously serialized current tab position.
    if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
        getSupportActionBar().setSelectedNavigationItem(
                savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    // Serialize the current tab position.
    outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
            .getSelectedNavigationIndex());
}

修改
我发现了这个问题。我使用AsyncTask收集将在选项卡中显示的所有信息,并在onPostExecute中添加标签。

onRestoreInstanceState之前调用

onPostExecute,因此标签计数仍为0。

2 个答案:

答案 0 :(得分:2)

尝试

if (savedInstanceState!= null && savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM) >= 0)

代替if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM))

答案 1 :(得分:1)

我不确定在旋转屏幕时是否调用onSaveInstanceState 由于this documentation,在将活动置于这样的背景状态之前调用onSaveInstanceState(Bundle)方法。

您是否检查过旋转屏幕时是否调用了该功能?