How to create Tab using TabHost and TabWidget in Android

In this android programming source code example, we are going to create Tab using TabHost and TabWidget in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to create Tab using TabHost and TabWidget in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ededed">

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </LinearLayout>
    </TabHost>
</RelativeLayout>

MainActivity.java

import android.app.TabActivity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TabHost;

import com.bluapp.androidview.R;

@SuppressWarnings("deprecation")
public class TabLayoutAndViewPagerActivity8 extends TabActivity {
    private TabHost tabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout_and_view_pager8);
        tabHost = (TabHost) findViewById(android.R.id.tabhost);

        TabHost.TabSpec TabMenu1 = tabHost.newTabSpec("First Tab");
        TabHost.TabSpec TabMenu2 = tabHost.newTabSpec("Second Tab");
        TabHost.TabSpec TabMenu3 = tabHost.newTabSpec("Third Tab");

        TabMenu1.setIndicator("Tab1");
        TabMenu1.setContent(new Intent(TabLayoutAndViewPagerActivity8.this, TabHostActivity.class));

        TabMenu2.setIndicator("Tab2");
        TabMenu2.setContent(new Intent(TabLayoutAndViewPagerActivity8.this, TabHostActivity.class));

        TabMenu3.setIndicator("Tab3");
        TabMenu3.setContent(new Intent(TabLayoutAndViewPagerActivity8.this, TabHostActivity.class));

        tabHost.addTab(TabMenu1);
        tabHost.addTab(TabMenu2);
        tabHost.addTab(TabMenu3);
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment