It's possible to enable/disable Tabs in ActionBar? With TabHost this is not a problem.. I do:
tabHost.getTabWidget().getChildAt(3).setVisibility(true);
and all works.. but if i want to do the same thing with Tabs in ActionBar??
In Tab class don't exist setEnable();
ActionBar bar = getActionBar();
Tab tab = bar.newTab();
tab.setText("Test");
tab.setEnable(false); /*DON'T EXIST!!*/
How can I do??
I haven't tested this - that will be up to you, but it should give you an general idea on how you could handle your problem.
There are three steps:
First step
We need something that can handle the enable/disable action for us. For this purpose we create the following class:
public class TabItem {
private Tab tab;
private Fragment fragment;
private boolean enabled;
public TabItem( Tab tab, Fragment fragment ) {
this.tab = tab;
this.fragment = fragment;
enabled = true;
}
public Tab getTab() {
return tab;
}
public Fragment getFragment() {
return fragment;
}
public void toggleEnabled() {
enabled = enabled ? false : true;
}
public boolean isEnabled() {
return enabled;
}
}
Second step
We need something that can hold these TabItems
and an easy way to access them. For this purpose we add the following class:
public class TabHolder {
private HashMap<Integer, TabItem> tabs;
public TabHolder() {
tabs = new HashMap<Integer, TabItem>();
}
public void addTab( TabItem tab ) {
tabs.put( tab.getTab().getPosition(), tab );
}
public TabItem getTab( int position ) {
return tabs.get( position );
}
}
Third step
We need to handle the selection of Tabs
ourselves, so we need to create a custom TabListener
:
private class MyTabListener implements TabListener {
@Override
public void onTabReselected( Tab tab, FragmentTransaction ft ) {
//Do nothing - unless you want to do something.
}
@Override
public void onTabSelected( Tab tab, FragmentTransaction ft ) {
TabItem item = tabHolder.getTab( tab.getPosition() );
if( item.isEnabled() ) {
ft.remove( item.getFragment() );
ft.commit();
}
}
@Override
public void onTabUnselected( Tab tab, FragmentTransaction ft ) {
//Do nothing - unless you want to do something.
}
}
Finally
We can now utilize our created framework. To do so, we need a TabHolder
:
tabHolder = new TabHolder(); //Needs to be declared in the same class as our TabListener
We need to add our Tabs
to this:
tabHolder.addTab( new TabItem( tab, fragmentForThisTab ) );
And we need to set our custom TabListener
on each Tab
:
tab.setTabListener( new MyTabListener() );
Enable/Disable
To enable or disable a Tab
we simply call:
tabHolder.getTab( position ).toggleEnabled();
Let me know how it goes :)
There is a simple way to remove the Tabs-bar from the Actionbar. Just type:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
This will remove any tabs-bar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With