Android ActionBar: show/hide tabs dynamically?

99封情书 提交于 2019-12-21 09:02:17

问题


Is it possible to remove/restore the tab bar from the action bar dynamically?

Up to now I did this by changing the navigation mode of the action bar. I used following code to remove and restore the tab bar:

@Override 
public void restoreTabs() {     
    getSupportActionBar()
    .setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    this.supportInvalidateOptionsMenu();
}

@Override
public void removeTabs() {      
    getSupportActionBar()
    .setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    this.supportInvalidateOptionsMenu();
}

That works, but there is a big problem: Everytime I call setNavigationMode, onTabSelected is called in the TabListener and the currently opend tab gets recreated.


回答1:


To remove the actionbar tabs dynamically, you simply need:

getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

To add them on the fly, simply do:

getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

For the second case, the assumption is that after setting the navigation mode, you will also add tabs, to the action bar, similar to this:

for (int resourceId : tabs) {
        actionBar.addTab(actionBar.newTab().setText(resourceId)
                .setTabListener(this));
}



回答2:


public void onDrawerClosed(View view) {
    getActionBar().setTitle(mTitle);
    // calling onPrepareOptionsMenu() to show action bar icons
    getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    invalidateOptionsMenu();
}

public void onDrawerOpened(View drawerView) {
    getActionBar().setTitle(mDrawerTitle);
    // calling onPrepareOptionsMenu() to hide action bar icons
    getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    invalidateOptionsMenu();
}



回答3:


This is working as intended, since the tab is being selected because it was not appearing. I suggest you to do by your own the control in TabListener.



来源:https://stackoverflow.com/questions/16298930/android-actionbar-show-hide-tabs-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!