Marcos Vasconcelos
Marcos Vasconcelos

Reputation: 18276

Keep selected NavigationItem trough orientation changes

I implemented for Android 3+ devices navigation of views trough 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;
          }
      });

This works as intended, but on orientation changes, the onNavigationItemSelected is called again with index = 0, returning my Activity to the first View.

How can I keep this state? And don't let onNavigationItem be called with index 0 onCreate?

EDIT:

Following Kirill answer, there's possible to store the current inedx, but there's a third view that ins't selectable trough NavigationList, and if I don't call setNavigationItemSelected after onCreate this will automatically fires with index = 0, returning the application to the first view.

This is my problem.

Upvotes: 3

Views: 907

Answers (1)

Kirill Kulakov
Kirill Kulakov

Reputation: 10245

You can extend the following function which will be excuted whenever the state of an activity might be lost,

@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"));
}

note that mDropMenu should be replace with your object, and you should use the appropriate method on it

Upvotes: 1

Related Questions