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 and the FrameLayout must have the id

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);

    // Create the FrameLayout (the content area)
    FrameLayout frame = new FrameLayout(context);
    LinearLayout.LayoutParams frameLayoutParams = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
    frameLayoutParams.setMargins(4, 4, 4, 4);

    // Create the container for the above widgets
    LinearLayout tabHostLayout = new LinearLayout(context);

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

    return tabHost;
  1. randomencoding posted this