Search code examples
androidandroid-tabhost

How to add images as a tab indicator in android tab host?


I am currently developing an application which a tab host is shown, each one of tab in the tab host is an activity. Now, what I want to do is to replace my text tab indicator as an image. These are the code that I used for implementing my tab host activity. TabHostActivity:

public class TabHostActivity extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabhost);

        TabHost tabHost = (TabHost) findViewById (android.R.id.tabhost);

        TabSpec tab1 = tabHost.newTabSpec("First Tab");
        TabSpec tab2 = tabHost.newTabSpec("Second Tab");
        TabSpec tab3 = tabHost.newTabSpec("Third Tab");

        tab1.setIndicator("Tab1");
        tab1.setContent(new Intent(this, Tab1Activity.class));
        tab1.setContent(new Intent(this, Tab1Activity.class));

        tab2.setIndicator("Tab2");
        tab2.setContent(new Intent(this, Tab2Activity.class));

        tab3.setIndicator("Tab3");
        tab3.setContent(new Intent(this, Tab3Activity.class));


        tabHost.addTab(tab1);
        tabHost.addTab(tab2);
        tabHost.addTab(tab3);

    }

}

As you can see on my code, I set Tab1, Tab2, Tab3 as my tab indicators, and want to replace this as an image

This is my activity_tabhost.xml

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
          android:id="@android:id/tabhost">

        <LinearLayout 
                android:id="@+id/LinearLayout01"
                android:orientation="vertical" 
                android:layout_height="fill_parent"
                android:layout_width="fill_parent">

                <TabWidget 
                    android:id="@android:id/tabs"
                    android:layout_height="wrap_content" 
                    android:layout_width="fill_parent">
                </TabWidget>

                <FrameLayout 
                    android:id="@android:id/tabcontent"
                    android:layout_height="fill_parent"
                     android:layout_width="fill_parent">
                </FrameLayout>

        </LinearLayout>

</TabHost>

Solution

  • Add images which you want to use in the tabs in the draw-able folder and get through this way.

    tab1.setIndicator("",getResources().getDrawable(R.drawable.tab1));
    tab2.setIndicator("",getResources().getDrawable(R.drawable.tab2));
    tab3.setIndicator("",getResources().getDrawable(R.drawable.tab3));