在屏幕旋转时保留选定的导航项目

3

我在Android 3+设备上实现了通过ActionBar NavigationMode(DROP_DOWN_LIST)导航视图的功能。

      getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

      SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list, android.R.layout.simple_spinner_dropdown_item);

      getActionBar().setListNavigationCallbacks(mSpinnerAdapter, new OnNavigationListener() {
          @Override
          public boolean onNavigationItemSelected(int index, long arg1) {
              if(index == 0)
                  selectHomeView();
              else
                  selectMainView();

              return true;
          }
      });

这个程序的运行是预期的,但在屏幕方向改变时,onNavigationItemSelected会再次调用,并返回到第一个视图。

我该如何保持这个状态?不让onNavigationItem在onCreate时被调用并且index为0?

编辑:

根据Kirill的答案,可以存储当前索引,但有第三个视图不能通过导航列表选择,如果我在onCreate后不调用setNavigationItemSelected,它将自动使用index = 0触发,并将应用程序返回到第一个视图。

这就是我的问题。

1个回答

1
你可以扩展以下函数,该函数将在活动状态可能丢失时执行。
@Override    
protected void onSaveInstanceState(Bundle savedInstanceState) {   
    super.onSaveInstanceState(savedInstanceState);
    // Save the state of the drop down menu
    savedInstanceState.putInt("selectedIndex",mDropMenu.getSelectedIndex());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
   super.onRestoreInstanceState(savedInstanceState);
   // Restore the state of the drop down menu
   mDropMenu.setSelectedIndex(savedInstanceState.getInt("selectedIndex"));
}

请注意,mDropMenu应替换为您的对象,并且您应该在其上使用适当的方法。

这个可以运行,但是有一个第三个视图没有在 NavigationList 中出现,并且不调用 setSelectedNavigationIndex 会默认触发它的索引为 0,这就是我的问题。 - Marcos Vasconcelos
1
可能相关 https://dev59.com/9mox5IYBdhLWcg3wr2Po - Kirill Kulakov
嗯...看起来重写 onNavigationItemSelected 是最好的解决方案,我会跟进这条线索。 - Marcos Vasconcelos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接