Android Creating Tab Layout with TabHost and TabWigdet or with FragmentTabHost and Fragment

In this tutorial, we are going to learn who to create a Tab Layout in android using TabHost and TabWigdet. After that, we will cover how to use FragmentTabHost and Fragment to achieve this result.

The FragmentTabHost is necessary when you want each individual Tab content to be represented by a single Fragment.

We first start with the TabHost and TabWigdet. If you want to implement Android Tab with Swipe Views, ViewPager, FragmentPagerAdapter, I wrote a tutorial on this topic. I will suggest you click the link and read it first.

What to do now. we will create our project in our IDE. For this tutorial, I am using the following tools and environment.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidTabHost

Package: com.inducesmile.androidtabhost

Select Blank Activity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

Now that we have created our project, open the default layout file (activity_main.xml) created for us by our IDE. This file is located at the res > layout folder

We will add a Button View control on top of our layout which we will use to navigate to the second activity page. The second activity page will hold the FragmentTabHost and Fragment part of this tutorial.

Under the button, we placed a TabHost widget with id equal to tabHost. The TabHost will contain a TabWidget with id equals to @android:id/tabs and a FrameLayout with id equals to @android:id/tabcontent.

Please note that these id values are important. If you choose to work with something else, there is every possibility that your application might crash.

We will add three LinearLayouts inside the FrameLayout. The FrameLayout is our container layout and it will use each of the LinearLayout for the Tab content.

In order to see that differences in LinearLayout contents, We will add an ImageView widget to each of the LinearLayout.

The code for the activity_main.xml is shown below. Copy and paste the code inside your layout file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androidtabhost.MainActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="16dp"
        android:padding="16dp"
        android:text="@string/second_example"
        android:textAllCaps="false"
        android:layout_alignParentTop="true"/>
    <TabHost
        android:id="@+id/tabHost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
            </TabWidget>
            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <LinearLayout
                    android:id="@+id/first_Tab"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:contentDescription="@string/app_name"
                        android:src="@drawable/tabone"
                        android:layout_marginTop="40dp"
                        android:layout_gravity="center_horizontal"/>
                </LinearLayout>
                <LinearLayout
                    android:id="@+id/second_Tab"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:contentDescription="@string/app_name"
                        android:src="@drawable/tabtwo"
                        android:layout_marginTop="40dp"
                        android:layout_gravity="center_horizontal"/>
                </LinearLayout>
                <LinearLayout
                    android:id="@+id/third_Tab"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">
                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:contentDescription="@string/app_name"
                        android:src="@drawable/tabthree"
                        android:layout_marginTop="40dp"
                        android:layout_gravity="center_horizontal"/>
                </LinearLayout>
            </FrameLayout>
        </LinearLayout>
    </TabHost>
</RelativeLayout>

The image files will used for the ImageView source attribute can be find in the res > drawable folder of this tutorial source code. You can replace these images with your own images if you desire.

Lets move over to the MainActivity.java, In this Activity class, we will obtain the instance of our button view and wire a click event listener so that when this button is clicked, it will take us to another activity page.

This will help you understand android TabHost more – TabHost is the container for a tabbed window view. This object holds two children: a set of tab labels that the user clicks to select a specific tab, and a FrameLayout object that displays the contents of that page. The individual elements are typically controlled using this container object, rather than setting values on the child elements themselves.

We will obtain the instance of the TabHost, call the setUp() of this class and add the TabSpec. From the code below you can see that it is basically simple to set this up. Copy and paste the code below to your activity class.

MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, FragmentTabExampleActivity.class);
                startActivity(intent);
            }
        });
        TabHost mTabHost = (TabHost)findViewById(R.id.tabHost);
        mTabHost.setup();
        //Lets add the first Tab
        TabHost.TabSpec mSpec = mTabHost.newTabSpec("First Tab");
        mSpec.setContent(R.id.first_Tab);
        mSpec.setIndicator("First Tab");
        mTabHost.addTab(mSpec);
        //Lets add the second Tab
        mSpec = mTabHost.newTabSpec("Second Tab");
        mSpec.setContent(R.id.second_Tab);
        mSpec.setIndicator("Second Tab");
        mTabHost.addTab(mSpec);
        //Lets add the third Tab
        mSpec = mTabHost.newTabSpec("Third Tab");
        mSpec.setContent(R.id.third_Tab);
        mSpec.setIndicator("Third Tab");
        mTabHost.addTab(mSpec);
    }
}

The output result of what we have done now is shown below. Feel free to modify this code to suit what your are planning to achieve.

When you run your application, your app interface will appear similar to the screen-shots shown below.

android TabHost and Tab widget

Android Creating Tab Layout with FragmentTabHost and Fragment

Since we are done with creating Tab Layout with TabHost and Tab Widget, we will focus our attention now on how we can achieve the same result by using FragmentTabHost and Fragment.

We will not repeat most of the steps that we have covered in the first part. Now, we will create a new Activity page by right clicking on your package folder. On the fly-out menu, select New and on the subsequent menu, select Activity and then click on BlankActivity menu. Name the new activity file – FragmentTabExampleActivity and click finish.

This will generator a new Activity page with its corresponding layout file. The layout file content will not be exactly the same like the first layout file.

Here, we will not add the LinearLayouts unlike before. The FrameLayout will serve as the container view and each select Fragment will be dynamically added to the FrameLayout.

Copy and paste this code to your activity_fragment_tab_example.xml

activity_fragment_tab_example.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.androidtabhost.FragmentTabExampleActivity">
    <android.support.v4.app.FragmentTabHost
        android:id="@+id/tabHost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </TabWidget>
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </FrameLayout>
    </android.support.v4.app.FragmentTabHost>
</RelativeLayout>

In the Activity class, we will inherit from FragmentActivity. Notice that we are using FragmentHost which is present in Android Support Library version 4. If you use the previous android TabHost widget, there will be a compatibility issues in your application.

We will get the instance of the FragmentHost and call the setUp() method of the class. The method takes, context, an instance of a FragmentManager and the container id.

Copy and paste the code below to your activity class.

FragmentTabExampleActivity

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
public class FragmentTabExampleActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_tab_example);
        FragmentTabHost mTabHost = (FragmentTabHost)findViewById(R.id.tabHost);
        mTabHost.setup(FragmentTabExampleActivity.this, getSupportFragmentManager(), android.R.id.tabcontent);
        mTabHost.addTab(mTabHost.newTabSpec("First Tab").setIndicator("First Tab"), new FirstFragment().getClass(), null);
        mTabHost.addTab(mTabHost.newTabSpec("Second Tab").setIndicator("Second Tab"), new SecondFragment().getClass(), null);
        mTabHost.addTab(mTabHost.newTabSpec("Third Tab").setIndicator("Third Tab"), new ThirdFragment().getClass(), null);
    }
}

Run your application and see for yourself what we have just created.

This brings us to the end of this tutorial, If you find anything confusing kindly contact me with your questions or use the comment box below.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new post once it is published.

Please if you love this tutorial, kindly download my new android app – Daily Pocket Calculator – in Google Play Store and let me know what you think about it.

Add a Comment