Due to limitation of Android Tab component I created a custom TabWidget that I am using in couple different projects already. The widget allows us to add custom background and use custom icons, tabs can be Top/Bottom aligned.
Currently tabs can launch new Activity and Dialog , when starting new Activity we can use “startActivityForResult” so our tab will get a notification when other activity have finished.
This is not a perfect solution as there are some drawbacks to it but it suits me well so I will stick to it till something better comes along; Hint Android gurus we need to be able to start new activities inside existing tab with more customization.
Creating a Tab
There a two thing that a tab needs
- Icon: either R.drawable.id or Drawable Object
- An Activity set via Intent or Dialog
Tab homeTab=new Tab(context, "HOME");
homeTab.setIcon(R.drawable.home);
homeTab.setIconSelected(R.drawable.home_selected);
homeTab.setIntent(new Intent(context, CarmeLauncher.class));
What is a TabHost ?
TabHost host tabs and specify how they will be rendered , TabViewConfig is used to configure the TabHost
TabHost tabHost=new TabHost(
new TabViewConfig()
.context(context)
.headerResourceId(R.drawable.tab_background_55)
.separatorId(R.drawable.separator)
.orientation(TabHost.Orientation.BOTTOM)
);
I use fluent interfaces or as some call it Builder pattern for configuring TabHost I think its straight forward and intuitive.
Binding tabs to Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Our Tab provider
TabHostProvider tabProvider=new CarmeTabProvider(this);
TabHost tabHost=tabProvider.getTabHost("main");
//This is the content of the tab
tabHost.setCurrentView(R.layout.main);
setContentView(tabHost.render());
}
To make tab selected we need to retrieve it using tab assigned TAG name in this case “HOME” beforesetContentView(tabHost.render())
is called.
Tab home=tabHost.getTab("HOME");
home.setSelected(true);
setContentView(tabHost.render());