ActionBar Dropdown Spinner item defaults to first item

Taranfx picture Taranfx · Dec 13, 2011 · Viewed 14.9k times · Source

I'm trying to set the index of the item that needs to be selected in the spinner by default, but it always defaults to 0 (1st item)

actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

SpinnerAdapter spinnerAdapter =
            new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_dropdown_item,
                    names);
int selectedIndex = actionBar.getSelectedNavigationIndex();
if (selectedIndex != targetIndex) {
    actionBar.setSelectedNavigationItem(targetIndex);
}

Above if block is called always. Even after setting index 2, next time I check it returns 0.

Edit: I suspect getSelectedNavigationIndex gives index of actionBar item rather than Spinner dropdown item. If that is the case, what method sets the index of selected item inside dropdown?

Answer

Roman picture Roman · Feb 12, 2012

Make sure you call setListNavigationCallbacks method before changing selected element. I can't see it in your example, so I think that's the problem.

Here is an example:

actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, this);
actionBar.setSelectedNavigationItem(position);

It works in my app without any problems.