Android: Programmatically setting up a TabHost

To create a TabHost using just code, you have to understand how the control is designed in XML. In particular, it’s important to keep in mind that the constituent parts of the TabHost are created by you — this means the placement of the tabs and the content pane are up to you to define. In other words, you’ll need to organize the tabs (TabWidget) and the content pane (FrameLayout) within a container (such as LinearLayout) and place this container inside the TabHost.

Furthremore, you’ll need to make sure that your TabWidget and FrameLayout are set up with specific ids that identify their role within the TabHost. Specifically, the TabWidget must have the id android.R.id.tabs and the FrameLayout must have the id android.R.id.tabcontent.

Now we have enough information to define a static method createTabHost:

public static TabHost createTabHost(Context context) {
    // Create the TabWidget (the tabs)
    TabWidget tabWidget = new TabWidget(context);
    tabWidget.setId(android.R.id.tabs);

    // Create the FrameLayout (the content area)
    FrameLayout frame = new FrameLayout(context);
    frame.setId(android.R.id.tabcontent);
    LinearLayout.LayoutParams frameLayoutParams = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
    frameLayoutParams.setMargins(4, 4, 4, 4);
    frame.setLayoutParams(frameLayoutParams);

    // Create the container for the above widgets
    LinearLayout tabHostLayout = new LinearLayout(context);
    tabHostLayout.setOrientation(LinearLayout.VERTICAL);
    tabHostLayout.addView(tabWidget);
    tabHostLayout.addView(frame);

    // Create the TabHost and add the container to it.
    TabHost tabHost = new TabHost(context, null);
    tabHost.addView(tabHostLayout);
    tabHost.setup();

    return tabHost;
}
  1. randomencoding posted this