Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

android - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...