In this blog we will create android TabLayout with ViewPager and Fragments.

TabLayout

TabLayout provides a horizontal layout to display tabs. We can set multiple views in single screen by using TabLayout. User can swipe right or left or click tab to open view. Here I have used ViewPager to swipe between Fragments.

ViewPager

The ViewPager is the widget that allows the user to swipe left to right or right to left  to see an entirely new screen. It means, it is just an easy and nicer way to show the user multiple tabs.

Follow the steps to create TabLayout.

Step 1. Create Android Project with an empty Activity called MainActivity.  As we have created Activity, two files activity_main.xml and MainActivity.java will be created in its correspondent folders. See project structure given at end of this blog. I have created project with name AndroidTabLayout.

Step 2. Please follow general setup steps before starting code.

1. Setup app/build.gradle file. Add com.android.support:design:23.1.1 design support library in it and Sync project after adding. You can compare your build.gradle file with following code.

app/build.gradle

apply plugin: 'com.android.application'

  

android {

    compileSdkVersion 23

    buildToolsVersion "26.0.1"

  

    defaultConfig {

        applicationId "com.example.androidtablayout"

        minSdkVersion 15

        targetSdkVersion 23

        versionCode 1

        versionName "1.0"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }

    }

}

  

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])

    testCompile 'junit:junit:4.12'

    compile 'com.android.support:appcompat-v7:23.1.1'

    compile 'com.android.support:design:23.1.1'     /* Add this dependency */

}

2. Add color codes in values/colors.xml.

values/colors.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <color name="colorPrimary">#3F51B5</color>

    <color name="colorPrimaryDark">#303F9F</color>

    <color name="colorAccent">#FF4081</color>

    <color name="colorWhite">#FFFFFF</color>

    <color name="colorLightGray">#E5E8E8</color>

</resources>

3. Now add fragments according to tabs you have to create. Here I will create three tabs that’s why I have added three Fragments in project.

Step to add fragment: Right click on app folder (at top of project hierarchy) -> New-> Fragment-> Fragment (Blank). Give proper name click Finish button.

See below code for home fragment.

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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:background="@color/colorLightGray"

    android:gravity="center"

    android:orientation="vertical"

    tools:context=".Home">

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Home"

        android:textColor="@color/colorPrimaryDark"

        android:textSize="35dp"

        android:textStyle="bold" />

  

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Hello..!! You are in Home Tab..!!"

        android:textColor="@color/colorPrimaryDark"

        android:textSize="16dp" />

  

</LinearLayout>

Home.java

package com.example.androidtablayout;

  

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

  

public class Home extends Fragment {

  

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /* Inflate the layout for this fragment */

        return inflater.inflate(R.layout.fragment_home, container, false);

    }

  

}

Please follow same step to create other fragments. 

Step 3. Create FragmentModel.java file which will have property to get and set fragments and title for Tabs of TabLayout.

Step to create java file: Right click to com.example.androidtablayout inside java folder-> New-> Java Class.

FragmentModel.java

package com.example.androidtablayout;

  

import android.support.v4.app.Fragment;

  

public class FragmentModel {

  

    Fragment tabFragment;

    private String tabTitle = "";

  

    /* Used to set Fragment and Title for Tabs of TabLayout*/

    public void setTabFragment(Fragment _tabFragment, String _tabTitle) {

        this.tabFragment = _tabFragment;

        this.tabTitle = _tabTitle;

    }

  

    /* Used to get Fragment for TabLayout */

    public Fragment getTabFragment() {

        return this.tabFragment;

    }

  

    /* Used to set and get Tab title for TabLayout */

    public String getTabTitle() {

        return this.tabTitle;

    }

  

}

Step 4. Create TabPagerAdapter.java file which will extend FragmentPagerAdapter and implements its Override methods getItem(int position), getCount() and getPageTitle(). This java file is used to help Pager to swipe tabs.

TabPagerAdapter.java

package com.example.androidtablayout;

  

import android.content.Context;

import android.support.v4.app.Fragment;

import android.support.v4.app.FragmentManager;

import android.support.v4.app.FragmentPagerAdapter;

import java.util.ArrayList;

  

public class TabPagerAdapter extends FragmentPagerAdapter {

  

    /* Initialize ArrayList */

    private ArrayList<FragmentModel> fList = new ArrayList<FragmentModel>();

  

    /* Constructor to class */

    public TabPagerAdapter(FragmentManager fm, ArrayList<FragmentModel> _fList) {

        super(fm);

        this.fList = _fList;

    }

  

    /* Override method getItem() which return current tab using position */

    @Override

    public Fragment getItem(int position) {

        return fList.get(position).getTabFragment();

    }

  

    /* Override method getCount() to return numbers of Tabs */

    @Override

    public int getCount() {

        return this.fList.size();

    }

  

    /* Override method getPageTitle() to return title of Tabs by position */

    @Override

    public CharSequence getPageTitle(int position) {

        return fList.get(position).getTabTitle();

    }

  

}

Step 5. Now open activity_main.xml file and modify it by adding android.support.design.widget.TabLayout and android.support.v4.view.ViewPager in it. TabLayout will show Tabs of multiple screens and ViewPager will help to swipe tabs.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity">

  

    <android.support.design.widget.TabLayout

        android:id="@+id/tabLayout"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:background="@color/colorPrimary"

        android:minHeight="?attr/actionBarSize"

        app:tabGravity="fill"

        app:tabMode="fixed"

        app:tabSelectedTextColor="@color/colorAccent"

        app:tabTextColor="@color/colorWhite" />

  

    <android.support.v4.view.ViewPager

        android:id="@+id/viewPager"

        android:layout_width="match_parent"

        android:layout_height="match_parent" />

  

</LinearLayout>

Step 6. Now we have to code in MainActivity.java file to show TabLayout and to set ViewPager with it. Add below code to MainActivity.java file.

MainActivity.java

package com.example.androidtablayout;

  

import android.support.design.widget.TabLayout;

import android.support.v4.view.ViewPager;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import java.util.ArrayList;

  

public class MainActivity extends AppCompatActivity {

  

    TabLayout tabLayout;

    ViewPager viewPager;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

  

        /* get a list of Fragments and Titles for TabLayout */

        ArrayList<FragmentModel> fList = fragmentList();

  

        /* Initialize ViewPager and Add Adapert to ViewPager */

        viewPager = (ViewPager) findViewById(R.id.viewPager);

        viewPager.setAdapter(new TabPagerAdapter(getSupportFragmentManager(), fList));

  

        /* Initialize TabLayout and Setup ViewPager with TabLayout */

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);

        tabLayout.setupWithViewPager(viewPager);

  

    }

  

    /* This function will return ArrayList of Fragments and Titles for Tabs */

    public ArrayList<FragmentModel> fragmentList() {

  

        ArrayList<FragmentModel> fList = new ArrayList<FragmentModel>();

        FragmentModel fModel;

  

        fModel = new FragmentModel();

        fModel.setTabFragment(new Home(), "Home");

        fList.add(fModel);

  

        fModel = new FragmentModel();

        fModel.setTabFragment(new Favorite(), "Favorite");

        fList.add(fModel);

  

        fModel = new FragmentModel();

        fModel.setTabFragment(new Profile(), "Profile");

        fList.add(fModel);

  

        return fList;

  

    }

  

}

Your Project Structure may look like,

Step 7. Now run this application in AVD or in your mobile. The output screen shown below. You can swipe right or left of click on tabs to navigate.