Implementing Fragment Tabs In Android

In this tutorial, you will learn how to implement fragment tabs in your Android application. Tabs allow the user to navigate among sibling screens by selecting the appropriate tab indicator available at the top of the display. In previous versions of Android, the tabs could be built using a TabWidget and TabHost. Unfortunately, these functionalities has been deprecated. We will create three tabs that contain fragments and on tab click will show the selected fragments. So lets begin…

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project FragmentTabsTutorial.

Application Name : FragmentTabsTutorial

Project Name : FragmentTabsTutorial

Package Name : com.androidbegin.fragmenttabstutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.fragmenttabstutorial;

import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {
	// Declare Tab Variable
	ActionBar.Tab Tab1, Tab2, Tab3;
	Fragment fragmentTab1 = new FragmentTab1();
	Fragment fragmentTab2 = new FragmentTab2();
	Fragment fragmentTab3 = new FragmentTab3();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ActionBar actionBar = getActionBar();

		// Hide Actionbar Icon
		actionBar.setDisplayShowHomeEnabled(false);

		// Hide Actionbar Title
		actionBar.setDisplayShowTitleEnabled(false);

		// Create Actionbar Tabs
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Set Tab Icon and Titles
		Tab1 = actionBar.newTab().setIcon(R.drawable.tab1);
		Tab2 = actionBar.newTab().setText("Tab2");
		Tab3 = actionBar.newTab().setText("Tab3");

		// Set Tab Listeners
		Tab1.setTabListener(new TabListener(fragmentTab1));
		Tab2.setTabListener(new TabListener(fragmentTab2));
		Tab3.setTabListener(new TabListener(fragmentTab3));

		// Add tabs to actionbar
		actionBar.addTab(Tab1);
		actionBar.addTab(Tab2);
		actionBar.addTab(Tab3);
	}
}

We have created three tabs with tab listeners and set the action bar to navigation mode tabs. For the first tab, we have set a custom tab icon and the other two with texts title. We have prepared a sample tab icon for this tutorial. Insert your downloaded sample tab icon into your res drawable-hdpi.

Sample Tab Icon

[wpfilebase tag=file id=29 tpl=download-button /]

Next, create an XML graphical layout for the MainActivity. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file activity_main.xml and paste the following code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Next, create a tab listener class. Go to File > New > Class and name it TabListener.java. Select your package named com.androidbegin.fragmenttabstutorial and click Finish.

Open your TabListener.java and paste the following code.

TabListener.java

package com.androidbegin.fragmenttabstutorial;

import android.app.ActionBar.Tab;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ActionBar;

public class TabListener implements ActionBar.TabListener {

	Fragment fragment;

	public TabListener(Fragment fragment) {
		// TODO Auto-generated constructor stub
		this.fragment = fragment;
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		ft.replace(R.id.fragment_container, fragment);
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub
		ft.remove(fragment);
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
		// TODO Auto-generated method stub

	}
}

This tab listener class manages the selected tab clicks and to show or remove a fragment.

Next, create a class for the first tab. Go to File > New > Class and name it FragmentTab1.java. Select your package named com.androidbegin.fragmenttabstutorial and click Finish.

Open your FragmentTab1.java and paste the following code.

FragmentTab1.java

package com.androidbegin.fragmenttabstutorial;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Fragment;

public class FragmentTab1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
        return rootView;
    }

}

Next, create a class for the second tab. Go to File > New > Class and name it FragmentTab2.java. Select your package named com.androidbegin.fragmenttabstutorial and click Finish.

Open your FragmentTab2.java and paste the following code.

FragmentTab2.java

package com.androidbegin.fragmenttabstutorial;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Fragment;

public class FragmentTab2 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragmenttab2, container, false);
        return rootView;
    }

}

Next, create a class for the third tab. Go to File > New > Class and name it FragmentTab3.java. Select your package named com.androidbegin.fragmenttabstutorial and click Finish.

Open your FragmentTab3.java and paste the following code.

FragmentTab3.java

package com.androidbegin.fragmenttabstutorial;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Fragment;

public class FragmentTab3 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragmenttab3, container, false);
        return rootView;
    }

}

Next, create an XML graphical layout for FragmentTab1. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file fragment1.xml paste the following code.

fragment1.xml

<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" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/Fragment1" />

</RelativeLayout>

Next, create  an XML graphical layout for FragmentTab2. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file fragmenttab2.xml and paste the following code.

fragmenttab2.xml

<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" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/Fragment2" />

</RelativeLayout>

Next, create  an XML graphical layout for FragmentTab3. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file fragmenttab3.xml and paste the following codes.

fragmenttab3.xml

<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" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/Fragment3" />

</RelativeLayout>

Next, change the application name and texts in strings.xml. Open your strings.xml and paste the following codes. Go to res > values > strings.xml
strings.xml

<resources>

    <string name="app_name">Fragment Tabs Tutorial</string>
    <string name="menu_settings">Settings</string>
    <string name="Fragment1">This is Fragment 1</string>
    <string name="Fragment2">This is Fragment 2</string>
    <string name="Fragment3">This is Fragment 3</string>

</resources>

In your AndroidManifest.xml, we need to set minSdkVersion to 13 to fulfil the requirement for FragmentTransaction. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.fragmenttabstutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output :

FragmentTabs ScreenShot

Source Code 

[purchase_link id=”7862″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

when add new fragment class within fragment please give me solution

mahadev dalvi

Implementing Fragment Tabs In Android

Can you please tell me how you can call a particular tab like TAB2 from an another activity using this code?

Anshul Tyagi

Implementing Fragment Tabs In Android

I think http://romannurik.github.io/AndroidAssetStudio/ will help you to change color of tab.

Harsh Bhakta

Implementing Fragment Tabs In Android

Scroll up, its defined in the activity_main.xml at the start

Papichulo

Implementing Fragment Tabs In Android