Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set active item in the Action Bar drop-down navigation?

I'm trying to fix the issue with restarting activity on orientation changes.

I have an ActionBar with drop-down list navigation and after every rotation first element of this list is being activated. Keeping fragment content wasn't difficult, but I don't know how to set active list item.

Here is the definition of ActionBar:

getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ArrayAdapter<CharSequence> list = ArrayAdapter
    .createFromResource(this, R.array.action_list, android.R.layout.simple_dropdown_item_1line);
list.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
getActionBar().setListNavigationCallbacks(list, this);

And here is my workaround:

@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    if (!application.isRotated) {
        application.activePosition = itemPosition;
        application.activeId = itemId;
        getFragmentManager().beginTransaction()
            .replace(android.R.id.content, MyFragment.newInstance(itemPosition))
            .commit();
    } else {
        application.isRotated = false;
        this.onNavigationItemSelected(application.activePosition, application.activeId);            
    }
    return true;
}

@Override
protected void onStop() {
    super.onStop();
    application.isRotated = true;
}

I'm not sure it's the best solution though.

like image 496
Roman Avatar asked Jan 27 '12 19:01

Roman


2 Answers

I just found that function. It is setSelectedNavigationItem(int position).

Set the selected navigation item in list or tabbed navigation modes.

Example:

actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, this);
actionBar.setSelectedNavigationItem(position);
like image 93
2 revs Avatar answered Nov 06 '22 23:11

2 revs


As of support library v7, you just need to save / restore the state of the ActionBar:

private static final String STATE_SELECTED_NAVIGATION_ITEM = "selectedNavItem";

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Restore the previously serialized current dropdown 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 dropdown position.
    outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
            .getSelectedNavigationIndex());
}
like image 1
David Chandler Avatar answered Nov 06 '22 23:11

David Chandler