Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 426
Marcos Vasconcelos Avatar asked Jun 07 '26 11:06

Marcos Vasconcelos


1 Answers

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

like image 73
Kirill Kulakov Avatar answered Jun 09 '26 02:06

Kirill Kulakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!