GWT – Hide Tabs in TabPanel
I was continuing my work on a sample GWT app and needed the ability to use a Menu with CheckItems to show/hide tabs in a tab panel. Here is how I did it.
Note: This post does not cover the creation of the TabPanel, Toolbar and ToolbarButton with a Menu.
Step 1: Override the Ext.TabPanel. (Note: This was just added to a JavaScript file I added to my application. I did not modify the ext-all.js file)
Ext.override(Ext.TabPanel, {
hideTabStripItem : function(item){
//Don't hide if its the last tab
var cnt = this.items.length;
var visibleTabs = 0;
for(var i = 0; i < cnt; i++ ){
if(!this.isTabStripItemHidden(i)){
visibleTabs++;
}
}
if(visibleTabs > 1){
item = this.getComponent(item);
var isactive = (item == this.activeTab);
var el = this.getTabEl(item);
if(el){
el.style.display = 'none';
this.delegateUpdates();
}
if(isactive){
//Set the next visible tab active
var curIndx = 0;
var indx = 0;
for(var i = 0; i < cnt; i++ ){
var tab = this.getComponent(i);
if(tab.id == item.id){
curIndx = i;
break;
}
}
//Check for the next available tab
for(var i = (curIndx+1); i < cnt; i++ ){
if(!this.isTabStripItemHidden(i)){
indx = i;
break;
}
}
if(indx == 0){
//Check for a tab before the current one
for(var i = 0; i < curIndx; i++ ){
if(!this.isTabStripItemHidden(i)){
indx = i;
break;
}
}
}
this.setActiveTab(indx);
}
}
if(visibleTabs == 1){
throw "Could not hide the tab";
}
},
unhideTabStripItem : function(item){
item = this.getComponent(item);
var el = this.getTabEl(item);
if(el){
el.style.display = '';
this.delegateUpdates();
}
this.setActiveTab(item);
},
isTabStripItemHidden : function(item){
item = this.getComponent(item);
var el = this.getTabEl(item);
if(el){
return el.style.display == 'none';
}
//return true since it does not exist.
return true;
}
});
Step 2: Create a CheckItem with a listener to show/hide the tab (add it to a ToolbarButton’s Menu).
public CheckItem createTabCheckItem(String menuTitle, final String tabId, final TabPanel tabPanel){
CheckItem ci = new CheckItem(menuTitle);
ci.addListener(new CheckItemListenerAdapter() {
public void onCheckChange(CheckItem item, boolean checked) {
if (checked) {
tabPanel.unhideTabStripItem(tabId);
} else {
try {
tabPanel.hideTabStripItem(tabId);
} catch (Exception e) {
item.setChecked(true);
}
}
}
});
ci.setHideOnClick(false);
return ci;
}