Friday, January 28, 2011

Adding tabs in android and placing them at the bottom of the screen


I was looking for a way to launch activities using android tabs that could be customized and placed at the bottom of the screen. After a lot of googling I could not find a workable solution to do so purely from code without using a layout file, so, after a bit of trial and error I was able to use TabActivity class for spawning activities and customize the existing TabHost structure which by default came with a "LinearLayout" element embedded while I required a "RelativeLayout" element within TabHost.

Here is the sample code:

public class TabApp extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost();  // The activity TabHost
        TabHost.TabSpec spec;  // Resusable TabSpec for each tab
        Intent intent;  // Reusable Intent for each tab
        tabHost.removeAllViews();
        TabWidget tabs = new TabWidget(this);
        tabs.setId(android.R.id.tabs);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        tabs.setLayoutParams(params);
        FrameLayout content = new FrameLayout(this);
        content.setId(android.R.id.tabcontent);
        content.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        RelativeLayout relative = new RelativeLayout(this);
        relative.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        relative.addView(content);
        relative.addView(tabs);
        tabHost.addView(relative);
        tabHost.setup();
      
        // Create an Intent to launch an Activity for the tab (to be reused)
        intent = new Intent().setClass(this, AndroidBrowser.class);

        // Initialize a TabSpec for each tab and add it to the TabHost
        spec = tabHost.newTabSpec("tag1")
          .setIndicator("tag1",res.getDrawable(R.drawable.cw))
                                  .setContent(intent);
        tabHost.addTab(spec);

        // Do the same for the other tabs
        intent = new Intent().setClass(this, CWBrowser.class);
        spec = tabHost.newTabSpec("tag2")
          .setIndicator("tag2",res.getDrawable(R.drawable.cw))
                                  .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass(this, CWBrowser.class);
        spec = tabHost.newTabSpec("tag3")
          .setIndicator("tag3",res.getDrawable(R.drawable.cw))
                                  .setContent(intent);
        tabHost.addTab(spec);
      
        tabHost.setCurrentTab(0);
    }