Android Design Support Library made our day easier by providing backward compatibility to number of material design components all the way back to Android 2.1. In Design support Library the components like navigation drawer, floating action button, snackbar, tabs, floating labels and animation frameworks were introduced. In this article we are going to learn how to implement material tabs in your apps.

Before going further, I suggest have a look at this tabs docs that defines do’s and don’ts while implementing tabs.

android design support library tab layout

1. Making the App Material

We’ll start this by creating a new project and applying the material theme. If you are not aware of android material design, my previous article Android Getting Started with Material Design gives you a good start.

1. In Android Studio, go to File ⇒ New Project and fill all the details required to create a new project. When it prompts to select a default activity, select Blank Activity and proceed.

2. Open build.gradle and add android design support library com.android.support:design:23.0.1

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
}

3. Open colors.xml located under res ⇒ values and add the below color values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#125688</color>
    <color name="colorPrimaryDark">#125688</color>
    <color name="textColorPrimary">#FFFFFF</color>
    <color name="windowBackground">#FFFFFF</color>
    <color name="navigationBarColor">#000000</color>
    <color name="colorAccent">#c8e8ff</color>
</resources>

4. Add the below dimensions to dimens.xml located under res ⇒ values.

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="tab_max_width">264dp</dimen>
    <dimen name="tab_padding_bottom">16dp</dimen>
    <dimen name="tab_label">14sp</dimen>
    <dimen name="custom_tab_layout_height">72dp</dimen>
</resources>

5. Open styles.xml located under res ⇒ values and add below styles. The styles defined in this styles.xml are common to all the android versions.

<resources>

    <style name="MyMaterialTheme" parent="MyMaterialTheme.Base">

    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

6. Now under res, create a folder named values-v21. Inside values-v21, create another styles.xml with the below styles. These styles are specific to Android 5.0

<resources>

    <style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>

</resources>

7. Finally open AndroidManifest.xml and modify the theme to our customized theme by changing the android:theme attribute value.

android:theme="@style/MyMaterialTheme"
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.materialtabs" >

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

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

Run the app and verify the material theme by observing the notification bar color. If you see the notification bar color changed, it means that the material design theme is applied successfully.

android-material-design

Now we have our app material ready. So let’s start adding the tabs. But before that we’ll create few fragment activities for testing purpose. All these fragment activities contains very simple UI with only one TextView.

8. Under your main package create a fragment named OneFragment.java and add the below code.

package info.androidhive.materialtabs.fragments;

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

import info.androidhive.materialtabs.R;


public class OneFragment extends Fragment{

    public OneFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_one, container, false);
    }

}

9. Open fragment_one.xml located under res ⇒ layout and do the below changes.

<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"
    tools:context="info.androidhive.materialtabs.fragments.OneFragment">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/one"
        android:textSize="40dp"
        android:textStyle="bold"
        android:layout_centerInParent="true"/>

</RelativeLayout>

10. Likewise create few more fragment activities with same code we used for OneFragment.java. I have created TwoFragment.java, ThreeFragment.java, FourFragemnt.java ….. upto TenFragment.java

2. Fixed Tabs

Fixed tabs should be used when you have limited number of tabs. These tabs are fixed in position. In android design support library lot of new elements like CoordinatorLayout, AppBarLayout, TabLayout and lot more were introduced. I won’t cover all of these as it’s not the agenda of this article.

11. Open the layout file of main activity (activity_main.xml) and add below layout code.

app:tabMode – Defines the mode of the tab layout. In our case the value should be “fixed

<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />
</android.support.design.widget.CoordinatorLayout>

12. Open MainActivity.java and do the below changes.

tabLayout.setupWithViewPager() – Assigns the ViewPager to TabLayout.

setupViewPager() – Defines the number of tabs by setting appropriate fragment and tab name.

ViewPagerAdapter – Custom adapter class provides fragments required for the view pager.

package info.androidhive.materialtabs.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

import info.androidhive.materialtabs.R;
import info.androidhive.materialtabs.fragments.OneFragment;
import info.androidhive.materialtabs.fragments.ThreeFragment;
import info.androidhive.materialtabs.fragments.TwoFragment;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OneFragment(), "ONE");
        adapter.addFragment(new TwoFragment(), "TWO");
        adapter.addFragment(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

Now run the app. You should able to see the tabs displayed with swipe functionality between the tabs.

android-material-design-tab-layout

2.1 Full Width Tabs

If you want the tabs to be occupied the fullwidth of the screen, you need to assign app:tabGravity=”fill” to our TabLayout.

android-tab-layout-landscape-view

2.2 Center Aligned Tabs

If you want to keep your tabs horizontally centered, assign app:tabGravity=”center” to TabLayout.

android-tab-layout-gravity-center

3. Scrollable Tabs

The scrollable tabs should be used when you have many number of tabs where there is insufficient space on the screen to fit all of them. To make the tabs scrollable, set app:tabMode=”scrollable” to TabLayout.

13. Open activity_main.xml and change the app:tabMode to scrollable.

<android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"/>

14. Edit MainActivity.java and add few fragments to ViewPager in setupViewPager() method. I have added total of 10 fragments to ViewPager. After the changes, your main activity should look like below.

package info.androidhive.materialtabs.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OneFragment(), "ONE");
        adapter.addFrag(new TwoFragment(), "TWO");
        adapter.addFrag(new ThreeFragment(), "THREE");
        adapter.addFrag(new FourFragment(), "FOUR");
        adapter.addFrag(new FiveFragment(), "FIVE");
        adapter.addFrag(new SixFragment(), "SIX");
        adapter.addFrag(new SevenFragment(), "SEVEN");
        adapter.addFrag(new EightFragment(), "EIGHT");
        adapter.addFrag(new NineFragment(), "NINE");
        adapter.addFrag(new TenFragment(), "TEN");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

Now if you run the app, you can see the more number of tabs with scrollable functionality.

android-scrollable-tab-layout
android-scrollable-tab-layout-horizontal

4. Tabs with Icon & Text

Sometimes you might wanted to add an icon to Tab. Earlier adding an icon to tab is tedious process. But with the design support library it is very easy. All you have to do is call setIcon() method by passing appropriate icon. The icon will be placed in front of tab label.

tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);

15. Open your MainActivity.java and modify the code as below. Here I have added a new method called setupTabIcons() in which I have set all the tab icons.



import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.ic_tab_favourite,
            R.drawable.ic_tab_call,
            R.drawable.ic_tab_contacts
    };

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
    }

    private void setupTabIcons() {
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OneFragment(), "ONE");
        adapter.addFrag(new TwoFragment(), "TWO");
        adapter.addFrag(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

android-tab-layout-with-icon-and-text

5. Tabs with only Icons

Setting only icon to tab is same as setting text and icon except the method getPageTitle() in ViewPagerAdapter class returns null instead of tab label.

16. Open MainActivity.java and modify the getPageTitle() method as below and run the project.

        @Override
        public CharSequence getPageTitle(int position) {

            // return null to display only the icon
            return null;
        }

android-tab-layout-with-only-icons

6. Custom Tab View with Icon & Text

Setting a custom view to the tab is very useful when you are not able to achieve desired output by following the methods provided by tab layout. While setting a custom view to tab, make sure that you follow the specs suggested by android for tabs.

When we set the tab an icon and text, you can see the icon is horizontally aligned with tab text. But if you want to place the icon above the tab label, you have to use a custom view to achive it.

17. Under res ⇒ values, create an xml file named fonts.xml and add below string value. This xml file defines the font family for the tab label.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="font_fontFamily_medium">sans-serif</string>
</resources>

18. Under res ⇒ values-v21, create another xml named fonts.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="font_fontFamily_medium">sans-serif-medium</string>
</resources>

19. Open activity_main.xml and set the custom height to TabLayout. Setting this height is important as placing icon above the tab label takes more space than normal.

 <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="@dimen/custom_tab_layout_height"
            app:tabMode="fixed"
            app:tabGravity="fill"/>

20. Create an xml layout named custom_tab.xml under res ⇒ layout. In this layout we have defined the custom view for the tab.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tab"
    android:textColor="@color/colorAccent"
    android:textSize="@dimen/tab_label"
    android:fontFamily="@string/font_fontFamily_medium"/>

21. Open MainActivity.java and modify the code as below. Here if you observe setupTabIcons() method, I have rendered custom_tab.xml layout in each tab using below lines of code.

        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText("ONE");
        tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0);
        tabLayout.getTabAt(0).setCustomView(tabOne);

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import info.androidhive.materialtabs.R;
import info.androidhive.materialtabs.fragments.OneFragment;
import info.androidhive.materialtabs.fragments.ThreeFragment;
import info.androidhive.materialtabs.fragments.TwoFragment;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.ic_tab_favourite,
            R.drawable.ic_tab_call,
            R.drawable.ic_tab_contacts
    };

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
    }

    private void setupTabIcons() {

        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText("ONE");
        tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0);
        tabLayout.getTabAt(0).setCustomView(tabOne);

        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabTwo.setText("TWO");
        tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_call, 0, 0);
        tabLayout.getTabAt(1).setCustomView(tabTwo);

        TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabThree.setText("THREE");
        tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_contacts, 0, 0);
        tabLayout.getTabAt(2).setCustomView(tabThree);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OneFragment(), "ONE");
        adapter.addFrag(new TwoFragment(), "TWO");
        adapter.addFrag(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

Now if you run the app, you can see the icon placed above the tab label.

android-tab-layout-with-custom-view-icon-and-text

I hope this article provided useful information about the tab layout using design support library. If you have any queries please do comment below.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Thank you Ravi! You always rule!

  • Amol Chavhan

    Plz Add at least one project on Widgets , Your posts are easy to understand Thank you !

  • Adi Gunawan

    followed you since 2012, still amazing.

  • Harshank Sananse

    Awesome Ravi keep it up.

  • Norby Baruani

    Thanx Ravi for this awesome work. Keep up the hard work.
    Will it possible for you to do a tutorial on responsive android design for different screen size, tablet and as well landscape!?

  • Tigani

    thank you Ravi always awesome work

  • Thank you so much 🙂

  • baaslaawe

    THANK YOU lecture , can i use old android api such as 2.3, and also used like navigation drawer action bar and fragment old android thanks

  • Ramiro Madriaga

    great, thanks from argentina

  • Asaad

    hi Ravi, i want to subscribe you but your website does not send verifying email to me

    • Please use facebook login for subscribing.

  • Mahmoud Bakr

    Thank you Ravi . but download code not work.

    • Are you getting any error?

      • I also try to download the code and while I enter my email address, I never receive the confirmation email.

        • Pls use facebook login. Right now amazon email server is down and can’t be solved easily.

          • Ok. I did login with FB but FYI the problem with “regular” login is there for a couple of weeks. I remember I was trying to download some of your code weeks ago with the same login problem.

          • Yeah, my Amazon SES account is blocked due to too many spam email address.

  • Rahul

    Hi… i’m new to Android… and following your tutorial.. i’m unable to use “TabLayout”… it shows no class exist.

    • Did you added the design support library in build.gradle?

      • Rahul

        Yes i’ve added that…

        • Okay. Can you give me exact error message.

      • Rahul

        Done…!!
        Actually there was a gradle sync error…!!

        P.S – Your work is very cool..!!
        Thanxxx

        • Okay. After adding something in build, you need to rebuild the project 🙂

          • Rahul

            Hi.. i’m doing same what you have described, my scroll functionality is working.. but i’m unable to tap on tabs..!
            Only scroll is working… taps not responding on touch!

    • You have to add the design support library to your build.gradle and rebuid the project

      • Rahul

        I’ve done that… Now my tabs are visible i can scroll through them but i’m unable to access them by tapping… only scroll is working..!

  • Arpit Aggarwal

    Thank you Ravi…

    Pls add a project for all the amazing features of android design support library like floating labels for editing text, floating action button, snackbar, collapsing toolbars etc…..your tutorials are awesome…

    • Yeah I started preparing one by one but got occupied with other work.

      • Tigani Jaber

        keep going your the best forever

  • Trey Rosius

    tabs with icons…#guru

  • Mohammad

    Thank you Ravi! You always rule!

  • Nirav Jain

    Hello Ravi…
    Tutorials can’t be so much easy than this…
    I was able to create Scrollable tabs…
    but i am having problem in setting webview in onefragment.xml
    i have set permissions right in androidmanifest…
    i am successfully able to set webview in blank activity project but unable to get it working in your scrollable tabs project
    if you can help me with some webview code

  • Mahesh Kanduri

    hi ravi i need help for ur side i need to set the default alarms for different timings if you can help me with some alarm code

  • PrabhuRaja Alagar

    HI Ravi,i need one help from u… how to handle back button in fragment

  • Kamal

    Hi Ravi! In case of custom view icon & text, I have a listview in view for two fragments. But1.5 rows of that listview is hiding behind the toolbar. Can you help me with this ?

    • Yeah, I have seen this problem but couldn’t get solution to it. Temporarily you can add margin top to your ListView equal to toolbar height.

      • Kamal

        me too did the same solution. So where do you work and from how many years you are working on android?

        • I am a full time blogger and freelancer. I have 4yrs of experience in Android. Check my other skills here 🙂

          http://in.linkedin.com/pub/ravi-tamada/26/457/a12

          • Kamal

            Thanks for sharing . . . you have a great passion for android. I liked your tutorial, they are so easy to understand and implement. Will be implementing all your examples soon. You are learning all this by your own?

          • Yes, I learn by my own. I mostly read android docs.

          • Harry Dessieu

            I actually ran into the same issue but the
            android:layout_margintop=”?attr/actionBarSize” presented many other issues. Eventually I found that adding
            app:layout_behavior=”@string/appbar_scrolling_view_behavior”

            to the view pager did the trick… Hopefully this will save someone hours of trial and errors

          • Cool.

          • Colaguy

            “app:layout_behavior=”@string/appbar_scrolling_view_behavior”
            did not work for me!
            The Listview is still missing the last row, it is hidden.
            Image: http://i60.tinypic.com/51voes.png

            Does anyone know how to fix this?

      • Ahmed Alkibsi

        Hi Ravi , Thx for lesson was help me .

    • Use below attribute to your ViewPager.

      app:layout_behavior=”@string/appbar_scrolling_view_behavior”

      • Kamal

        worked nicely!! Thanks man.

  • jhony

    hi Ravi,awesome tutorial,please i want to be able to scroll the tabs by tapping the respective header or text without swiping,(Like BBM) please how do i achieve that..thanks

  • Syahir Amir

    Hey Ravi, how do i invoke the back button on the action bar?

    • If you want to see the back arrow in action bar, you have to add android:parentActivityName=”” to the activity.

      To be notified whenever user presses the back button, add the below code in your activity.

      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      // Respond to the action bar’s Up/Home button
      case android.R.id.home:
      // write your code here
      return true;
      }
      return super.onOptionsItemSelected(item);
      }

  • jhony

    Mr Ravi please how to make the tab icons move the tabs without necessarily swiping the tabs

    • Can you explain your query detailed?

      • jhony

        for some reason i cant explain,when i click on the tab icons,the tabs do not move,even the action bar icons cannot be clicked,more like the whole screen is the Viewpager
        But i changed

        to just a RelativeVIew and it works fine.

        what could be wrong please? or do i just stick to the RelativeView

        • Rahul

          In Main_Activity.xml
          put “ViewPager” code into “AppBarLayout” .
          It will work…

          <android.support.design.widget.AppBarLayout

          • Rahul

            @ravi8x:disqus your work is really good…!

          • Thank you Rahul 🙂

  • Eder

    Ravi, great article, helped me a lot.

  • Gk’s

    Hello Ravi, Thanks for tutorial.

    I have a question, How to replace Theme or color of toolbar and status bar when click in another tab.

    • Gk’s

      if you can explain to the TabActivity no in Fragment.

      Thanks.

    • As of now dynamic theme switching is not supported.

      • Niharika88

        Hi, Ravi

        Thanks For the tutorial, its very helpful to me.

        I’m getting error in the values–>styles–> true

  • Okechukwu Eze

    Hi @Ravi Tamada
    I have been trying to combine this new MaterialTabSlids and the other MaterialDesign Drawer like i did the other time but this one seems a bit twisted as i keep getting error from “NavigationDrawerAdapter” on this code line

    adapter = new NavigationDrawerAdapter(getActivity(), getData());

    ERROR MESSAGE::

    ‘NavigationDrawerAdapter(android.content.Context, java.util.List)’ in ‘okechukwu.com.materialtab.adapter.NavigationDrawerAdapter’ cannot be applied to ‘(android.support.v4.app.FragmentActivity, java.util.List)’

    its really crappy for me to combine this time. WOuld appreciate if you can make it happen this time or direct me on how to go about it.

    • Sometime we unknowingly import two different packages. FragmentActivity can be imported using two diff packages.

      android.app.FragmentActivity

      or

      android.support.v4.app.FragmentActivity

      Make sure that you are importing same package in both classes. I suggest use android.support.v4.app.FragmentActivity in both the classes.

  • Bhuvanendran

    I am using eclipse and i got the following error …

    java.lang.NoClassDefFoundError: android.support.v7.app.AppCompatDelegateImplV14…

    how to resolve this

    • Simple, move to Android Studio. I should stop supporting Eclipse.

  • Syahir Amir

    Hello again Ravi!

    Do you know a way to swap fragments? Lets say there is a button on my first tab’s fragment and when I click on that button I want to change the first tab’s fragment to fragment four.

    Also, is there any way I can donate to your page? You helped me a lot with all the tutorials you have posted and I wish I can repay that!

  • Mstafa Dayanr

    * Hi Ravi. First, I want to say you did a great Job. It is a very detailed and useful tutorial. I have downloaded source code and applied into my own project.

    * Everything is great except one problem. Tabs don’t show full of my activities. They clipped the layout. I uploaded a picture of what I mean: http://s7.postimg.org/q7e9qu7dn/Soru_001.jpg

    How to fix this problem? If you help, i Will be gratefull to you.

    • Syahir Amir

      Ravi already answered this below
      Use below attribute to your ViewPager.

      app:layout_behavior=”@string/appbar_scrolling_view_behavior”

  • phong nt

    tuturial awesome, but i have problem that i have 3 fragment, when i unselect a tab and when back to that tab , it reload again ( i get data form Internet). so can i do repair it?

  • I am expecting a good tutorial about Gradle and some cool things we can done using it. Will you make a tutorial about them ? Pleasee 🙂

  • sneakysnoopy

    Hi Ravi, awesome article for a new comer like me. I need to integrate tabbed layout inside fragments since I am using navigation drawer using your other article. Now i need to create Tab fragments inside each of the drawer fragments. Can you guide me on what to do? Thanks

  • famalick

    Hey mate, I have implemented the TabLayout inside a Fragment cause my App is implemented Navigation Drawer also. Working fine on 5.0 and above but TabLayout is not showing on 4.4 devices. What could be the problem. Please help.

    • Are you testing on read device or emulator?

      • famalick

        I am testing it on real devices:
        Galaxy S5 with 5.0
        Galaxy Grand Prime with 4.4

  • Poyraz

    Hello Ravi,

    Learning Android programming from your website is a very unique experience 🙂 You’ve actually helped me a lot with your tutorials and there’s something I’d like to ask.

    I finished this tutorial but I have no idea how to customize the contents of these fragments. I cannot change anything. How can I do it? What should I learn to be able to do this? Can you give a little information about this issue? 🙂 I’m planning to add some cards and filling them with the data from my database with JSON. But for now, I cannot even change the default texts inside the fragments :))

    Your help will be very appreciated 🙂

    Thank you very much!

  • Mahmoud Ibrahim

    Hi Ravi

    it’s a great tutorial , but there is a problem ” You need to use a Theme.AppCompat theme (or descendant) with this activity.”
    i tried many solution for this , but the same error appears every time …

    • Can you post the complete error log.

      • Bilal Saeed

        i Ravi, Its so awesome tutorial. Can you tell me how to change color icon, text color when icon tabs selected (CustomViewIconTextTabsActivity)..?

  • Colaguy

    Listview problem: The last row is missing, because it is outside of the screen.
    “app:layout_behavior=”@string/appbar_scrolling_view_behavior” did not help me.
    I have an image: http://i60.tinypic.com/51voes.jpg

    Can anyone help me please. I have followed the guide and other similar guides, but the Viewpager is too long.

    • If you have added marginTop to ListView, remove that attribute.

  • Newbie

    Hi Ravi, Can you tell me how to add com.android.support:design:23.0.1 library in eclipse. I am not able to run this project in eclipse having lot of issues. But i managed some issue. I am keep getting this error “error: No resource identifier found for attribute ‘layout_scrollFlags’ in package ‘tab.android.tabsample'” in activity_custom_view_icon_text_tabs.xml layout. Please help me in solving this issue. I just copied all layout, styles from your sample code and pasted it in my sample app. Copied the package into my sample app the same way. I imported all the package name correctly in .Java file. Need help

    • Move to Android Studio. In Android Studio you can directly import the Eclipse project. It won’t take more than 2mins.

  • Bilal Ilyas

    Awsome Tutorial … Please can u upload a tutorial sample how to use drawer layout and sliding tabs combined together?

  • Nirav Jain

    I have successfully added total of 5 tabs in icon and text activity by changing the tabmode to gravity in activity_icon_text_tab.xml and adding adapter.addFrag to IconTextTabActivity

    but i am unable to add icons to new tabs

    here what i have done in IconTextTabsActivity class

    private int[] tabIcons = {
    R.drawable.ic_tab_favourite,
    R.drawable.ic_tab_call,
    R.drawable.ic_tab_contacts,
    R.drawable.ic_action_name,
    R.drawable.ic_action_sms
    };

    private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
    tabLayout.getTabAt(3).setIcon(tabIcons[3]);
    tabLayout.getTabAt(4).setIcon(tabIcons[4]);
    }

    private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new OneFragment(), “Home”);
    adapter.addFrag(new TwoFragment(), “CHAT”);
    adapter.addFrag(new ThreeFragment(), “Call”);
    adapter.addFrag(new FourFragment(), “Sms”);
    adapter.addFrag(new FiveFragment(), “About”);
    viewPager.setAdapter(adapter);
    }

  • Guilherme Schumacher

    Hey Ravi, great work with the tutorials… I’m having an issue though… In Android Device (Galaxy S6), the tabs can be clicked or swiped but in Android 4.4 (Galaxy S4 mini), just the swipe works.. Not even the ripple effect is reproduced on 4.4..

  • Renz Razon

    Can this still be done using eclipse? :/ men, i did not see this. This is much better than the tab layout with swipeable views

  • Yura Buyaroff

    The best! Great tnx!

  • Rajesh Koshti

    We have Implemented your code it’s awesome but we found one bug when we Start swipe First-Tab then Second-Tab is Visible but Third tab onStart() method call when we start swipe Second then Third-tab is Visible but Fourth-Tab onStart() method call please tell me why this happened

  • Hakan Atak

    Thank you Ravi. Nice Tutorial

  • Junaid TT

    Hi Ravi
    Your tutorials are very helpful for me ,as a beginner iam in trouble with the following code ..

    imports :

    import android.support.design.widget.TabLayout;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;

    onCreate:

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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    }

    Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’.

    > Compilation failed; see the compiler error output for details.
    Error:(28, 9) error: cannot find symbol method setupViewPager(ViewPager)

    Created Fragment and imports :

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

    dependencies :

    compile fileTree(dir: ‘libs’, include: [‘*.jar’])
    compile ‘com.android.support:appcompat-v7:23.0.1’
    compile ‘com.android.support:design:23.0.1’
    compile ‘com.android.support:support-v4:23.0.1’

    android {
    compileSdkVersion 23
    buildToolsVersion ‘23.0.1’

    defaultConfig {
    applicationId “com.example.junaidkodoor.material_designing”
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 1
    versionName “1.0”
    }
    buildTypes {

  • Junaid TT

    Hi ravi

    Your tutorials are very useful for me ,As a begginer am in trouble with folloing errors :

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

    Actual code :

    import android.support.design.widget.TabLayout;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;

    import com.example.junaidkodoor.material_designing.R;

    public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

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

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    }

    Also Created Fragments coade as below:

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

    import com.example.junaidkodoor.material_designing.R;

    /**
    * Created by junaidkodoor on 27/9/15.
    */
    public class OneFragment extends Fragment {

    public OneFragment() {
    // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_one, container, false);
    }
    }

    Dependencies :

    android {
    compileSdkVersion 23
    buildToolsVersion ‘23.0.1’

    defaultConfig {
    applicationId “com.example.junaidkodoor.material_designing”
    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’])
    compile ‘com.android.support:appcompat-v7:23.0.1’
    compile ‘com.android.support:design:23.0.1’
    compile ‘com.android.support:support-v4:23.0.1’
    }

  • parag jikadara

    Hi ravi

    i have a following error in a example

    01-12 06:16:02.577: E/AndroidRuntime(14160): FATAL EXCEPTION: main

    01-12 06:16:02.577: E/AndroidRuntime(14160): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.materialtabs/info.androidhive.materialtabs.activity.MainActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class android.support.design.widget.CoordinatorLayout

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.access$600(ActivityThread.java:162)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.os.Handler.dispatchMessage(Handler.java:107)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.os.Looper.loop(Looper.java:194)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.main(ActivityThread.java:5371)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Method.invokeNative(Native Method)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Method.invoke(Method.java:525)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at dalvik.system.NativeStart.main(Native Method)

    01-12 06:16:02.577: E/AndroidRuntime(14160): Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class android.support.design.widget.CoordinatorLayout

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.createView(LayoutInflater.java:613)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.inflate(LayoutInflater.java:466)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at info.androidhive.materialtabs.activity.MainActivity.onCreate(MainActivity.java:20)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.Activity.performCreate(Activity.java:5122)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)

    01-12 06:16:02.577: E/AndroidRuntime(14160): … 11 more

    01-12 06:16:02.577: E/AndroidRuntime(14160): Caused by: java.lang.reflect.InvocationTargetException

    01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Constructor.constructNative(Native Method)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.createView(LayoutInflater.java:587)

    01-12 06:16:02.577: E/AndroidRuntime(14160): … 21 more

    01-12 06:16:02.577: E/AndroidRuntime(14160): Caused by: java.lang.NoClassDefFoundError: android.support.design.R$styleable

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:171)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:165)

    01-12 06:16:02.577: E/AndroidRuntime(14160): … 24 more

    • Sivaram Ramadhas

      Parag, I found the solution

      Problem what i faced is R.Java file is not generated under support.design in gen/ folder. After doing the below steps R.Java file is generated. Main issue is “design” library is target to 22. Changing to 23 worked.

      1. Import support design library from sdkextrasandroidsupportdesign to eclipse workspace.

      2. Open project.properties of AppCompat and design Library and target it to 23

      3. Clean Appcompat, design and YourTabProject.

      4. Now every things goes good.

  • Bibaswann Bandyopadhyay

    Don’t we need to implement OnFragmentInteractionListener interface in MainActivity? I got an exception that showed that I need these implements from every fragments. I implemented those and it worked

  • Rajesh Koshti

    We have Implemented your code it’s awesome but we found one bug when we
    Start swipe First-Tab then Second-Tab is Visible but Third tab onStart()
    method call when we start swipe Second then Third-tab is Visible but
    Fourth-Tab onStart() method call please tell me why this happened

  • Sivaram Ramadhas

    Hi Ravi,

    I followed this blog and create a new project in eclipse using your sample source code. I am not getting any error in code. But during running the app i am getting an error on run time of the app. Please look into this question http://stackoverflow.com/questions/32838594/error-inflating-class-android-support-design-widget-coordinatorlayout-and-classn and help me. I am trying to solve this error from day before yesterday, nothing worked for me. Please help me.

  • Sivaram Ramadhas

    Hi Ravi,

    Scrollable tab is not working. I am seeing the Tab name as O, T, T, F..N,T instead of One, Two …Ten. While loading it shows as One, Two …Ten and after few seconds the Tab name become O, T, T, F..N,T and completely fit inside the screen. It is showing the first letter of Tab name and srink inside the screen. No option to scroll.

    app:tabMode=”scrollable” is already there in activity_scrollable_tab.xml

    Please help me in solve this.

    • Ashutosh Srivastava

      Just add in your activity onCreate method below getting tabLayout reference

      tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

  • parag jikadara

    Hi Ravi,

    i found error in a this project plz help me

    01-12 06:16:02.577: E/AndroidRuntime(14160): FATAL EXCEPTION: main

    01-12 06:16:02.577: E/AndroidRuntime(14160): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.materialtabs/info.androidhive.materialtabs.activity.MainActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class android.support.design.widget.CoordinatorLayout

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.access$600(ActivityThread.java:162)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.os.Handler.dispatchMessage(Handler.java:107)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.os.Looper.loop(Looper.java:194)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.main(ActivityThread.java:5371)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Method.invokeNative(Native Method)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Method.invoke(Method.java:525)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at dalvik.system.NativeStart.main(Native Method)

    01-12 06:16:02.577: E/AndroidRuntime(14160): Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class android.support.design.widget.CoordinatorLayout

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.createView(LayoutInflater.java:613)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.inflate(LayoutInflater.java:466)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.inflate(LayoutInflater.java:352)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:255)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at info.androidhive.materialtabs.activity.MainActivity.onCreate(MainActivity.java:20)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.Activity.performCreate(Activity.java:5122)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)

    01-12 06:16:02.577: E/AndroidRuntime(14160): … 11 more

    01-12 06:16:02.577: E/AndroidRuntime(14160): Caused by: java.lang.reflect.InvocationTargetException

    01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Constructor.constructNative(Native Method)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.view.LayoutInflater.createView(LayoutInflater.java:587)

    01-12 06:16:02.577: E/AndroidRuntime(14160): … 21 more

    01-12 06:16:02.577: E/AndroidRuntime(14160): Caused by: java.lang.NoClassDefFoundError: android.support.design.R$styleable

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:171)

    01-12 06:16:02.577: E/AndroidRuntime(14160): at android.support.design.widget.CoordinatorLayout.(CoordinatorLayout.java:165)

    01-12 06:16:02.577: E/AndroidRuntime(14160): … 24 more

  • vorziz

    Hi Ravi, Its so awesome tutorial. Can you tell me how to change color icon when icon tabs selected?

  • Noavellir

    Nice Tutorial Ravi!
    But I have a question… how pass data from the main activity to any of the fragments?
    Thank you… and again… Nice tutorial!!

  • Ņ̵̠͙͓̫̲͍̘̈́̅̌̈́͘̕ͅg̷̮͇̟̱̘̫̐̈́̀

    Why can not I download it?

  • GimmY

    Hi Ravi,
    I have 5 tabs, on tab 1 i have ListView and when swipe Tabs 1 to 2/3/4/5 or 2/3/4/5 to 1, the app functionality slowed, and Android Studio shows this row in logcat.

    I/Choreographer﹕ Skipped 50 frames! The application may be doing too much work on its main thread.

    Code of MainAcitiviy: http://i.imgur.com/LgoSsgb.png

    Code of Tab1: http://i.imgur.com/Hq52erh.png

    Code of ListAdapter: http://i.imgur.com/usUFAgL.png

    • Its not an error

      • GimmY

        Hmm have you any idea how to set it right.

        Thanks.

      • GimmY

        Hi Ravi, I found this problem.

        Images that are that placed in ListView and Background of Layout on Tab3, have shown the problem of slowdown of Apps.

        Now I have a request how to fix Image that not display problems.

  • Newbie

    Your tutorial is awesome. I am implementing the same in my project and it is working.Tab scrolling functionality is working fine in Lollipop and not working on Kitkat and Jelly bean device. Is it possible to implement to support this Tab scrolling functionality in Kitkat and Jelly bean devices.

    Up navigation also not working in Kitkat and Jelly bean devices. On clicking the Back Arrow it is not taking back to Parent activity in Kitkat and Jelly bean devices.

    Please update your sample with support for Kitkat and Jelly bean devices.

  • Newbie

    Hi Ravi, I created a sample in eclipse using the your source code. Tab scrolling is working in lallipop. But the same code is not working on Kitkat and Jelly bean device. On Kitkat and Jelly bean device i face two problem,

    1. When i scroll the Tab, Tab is scrolling along with page navigation in Jellybean and kitkat devices, but in lallipop Tab alone gets scroll and it is working file. For eg: if 1,2,3..10 are the Tab and if i scroll the Tab, it scroll and for each scroll the Layout gets navigated. If i scroll, Tab gets navigate to 2nd Tab and then 3rd and so on.

    2. Up navigation is not working in Jellybean and Kitkat devices. If i swipe the Toolbar, Tab scrolling is happening with page navigation (above mentioned issue).

    Can you tell me what could be the problem and in which portion i need to check and sort it. I can send you the APK file if you provide me the email for better understanding of the problem.

    I am new to android, need some help to fix this.

    Thanks

  • Prakhar

    Hi Ravi,
    How can I add List in these fragments.
    Please help me with.

  • Prakhar

    Hi Ravi,
    How can I add listview in these fregments.
    Could you please help.
    Thankz

  • Monk L

    Ravi,

    I have to show the ActionBar also along with toolbar.

    How to show default ActionBar using your material theme design in Tab application.

    What is the way to achieve this by using your sample application.

  • kaziolas

    dude, this tut sucks so bad, half stuff unexplained, non-working, just rubish. Copy paste code isnt a tutorial because no one can understand what they are doing! Before creating any java files you forgot to tell to create strings otherwise app wont run and so on and so on..

  • Naresh

    Ravi,
    This is great tutorial.
    i have implemented this functionality in in my project successfully. But tab names shows are all of all capital letters. How to show the tab names with capitalize the first character of a word.

    Thanks
    Naresh

  • Jorge C

    Hello, great tutorial as always. I have been trying to locate the tab custom view in the bottom of the screen. I was wondering if you can help me on how to put the tab custom view in the bottom of the screen.

    Best,

    Jorge C.

  • phan piseth

    How to refresh or reload fragment on tab reselect?please help….

  • bagosbanget

    How to pass variable value from tab 1 to tab 2 or tab 3?

    • Adrian Scarlatescu

      Hi @bagosbanget:disqus,

      Let’s say you have an activity called DemoActivity, and you have implemented a method there called demoMethod(). Here is an example of how you can call that method from the MainActivity:

      DemoActivity demoActivity = (DemoActivity ) adapter.getItem(1);
      demoActivity.demoMethod();

      Notice adapter.getItem(ITEM_NO)
      Where ITEM_NO is the number of your slide related to DemoActivity

      GL

  • Divyesh Jindal

    great work (Y)

  • Noha

    great tutorial. Whenever I make a new activity in this app actionbar text color is black, any help how can I make it white?

    • Noha

      I figured it out, thanks.

  • Anang

    Hi Ravi, Thank you for the tutorial. I used the lesson for fixed tabs but I am getting some error in my activity which i do not get int he main activity where i have not implemented tabs. Here is my error message :

    java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.

    • Anang

      I solved it now.

  • Francis

    Hi Ravi, Thank you for the tutorial ,I work well for me,
    But how can I move the tab to bottom of the screen

    • Dheeraj Parashar

      This might help you.

      • MartínSerrano

        You only change the CoordinatorLayout to RelativeLayout and add these parameters?
        android:layout_alignparentbottom=”true”
        app:tabgravity=”fill”
        app:tabmode=”fixed”

  • oscar rodriguez

    Great tutorial. Thank you.!

  • Richard

    Hi Ravi!
    Great tutorial thx!
    But i find a bug, when you switch between fragments, the position going wrong.
    Try it, use Toast.makeText in all fragments and you will see.
    If you have any solution pls tell me.
    Thanks in advice!

  • sri vatsava

    I am getting large icons when I apply custom view please help

  • Harish

    Thank you for this Tutorial. I was trying the Fixed Tab Bar and i the app crashes.
    I get the following error in Logcat

    11-20 10:41:43.606 11251-11251/com.example.harish.testslidetab E/Zygote﹕ Zygote: error closing descriptor

    libcore.io.ErrnoException: close failed: EBADF (Bad file number)

    at libcore.io.Posix.close(Native Method)

    at libcore.io.BlockGuardOs.close(BlockGuardOs.java:75)

    at com.android.internal.os.ZygoteInit.closeServerSocket(ZygoteInit.java:221)

    at com.android.internal.os.ZygoteConnection.handleChildProc(ZygoteConnection.java:879)

    at com.android.internal.os.ZygoteConnection.runOnce(ZygoteConnection.java:242)

    at com.android.internal.os.ZygoteInit.runSelectLoop(ZygoteInit.java:715)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:651)

    at dalvik.system.NativeStart.main(Native Method)

    it would be great if you could help

  • Harish

    The Problem was sorted out.
    Great Tutorial. Thank You.

  • Harish

    Hi Ravi. I was wondering if we could add a Scroll-able tab inside the Fragment.
    i.e. 3. Scrollable Tab inside 2. Fixed Tabs
    Request advice on it.

  • Koustubh Patel

    Hi Ravi,
    Thanks for nice Article.

    But, Swipe is not working for me. I am only able to change tab by on Clicking them.
    I have two tabs. Is there any other thing needs to be done.

  • Rishabh Goyal

    Hi Ravi,
    Very nice tutorial..thanks but I am facing android force close while running the application. I have updated the sdk to 23. I have added android.support.v7.appcompat
    and design in the library of the application. Below are the logs.

    11-27 13:05:12.246: E/AndroidRuntime(14135): java.lang.NoClassDefFoundError: android.support.v7.widget.TintManager
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.support.design.widget.TabLayout$TabView.(TabLayout.java:1185)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.support.design.widget.TabLayout.createTabView(TabLayout.java:656)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.support.design.widget.TabLayout.addTabView(TabLayout.java:695)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.support.design.widget.TabLayout.addTab(TabLayout.java:386)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.support.design.widget.TabLayout.addTab(TabLayout.java:361)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.support.design.widget.TabLayout.setTabsFromPagerAdapter(TabLayout.java:645)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.support.design.widget.TabLayout.setupWithViewPager(TabLayout.java:616)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at info.androidhive.materialtabs.activity.SimpleTabsActivity.onCreate(SimpleTabsActivity.java:40)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.app.Activity.performCreate(Activity.java:5343)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.app.ActivityThread.access$800(ActivityThread.java:151)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.os.Handler.dispatchMessage(Handler.java:110)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.os.Looper.loop(Looper.java:193)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at android.app.ActivityThread.main(ActivityThread.java:5333)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at java.lang.reflect.Method.invokeNative(Native Method)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at java.lang.reflect.Method.invoke(Method.java:515)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
    11-27 13:05:12.246: E/AndroidRuntime(14135): at dalvik.system.NativeStart.main(Native Method)
    11-27 13:05:12.450: E/NetworkScheduler.SchedulerReceiver(23222): Invalid parameter app
    11-27 13:05:12.450: E/NetworkScheduler.SchedulerReceiver(23222): Invalid package name : Perhaps you didn’t include a PendingIntent in the extras?
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): null
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): java.lang.NullPointerException
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at com.google.android.gms.gass.a.a.computeSerializedSize(SourceFile:128)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at com.google.protobuf.nano.k.getSerializedSize(SourceFile:65)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at com.google.protobuf.nano.k.toByteArray(SourceFile:100)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at com.google.android.gms.gass.a.a(SourceFile:80)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at com.google.android.gms.gass.h.a(SourceFile:75)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at com.google.android.gms.gass.h.a(SourceFile:24)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at com.google.android.gms.chimera.e.run(SourceFile:179)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at com.google.android.gms.common.util.a.c.run(SourceFile:17)
    11-27 13:05:12.506: E/AsyncTaskServiceImpl(15008): at java.lang.Thread.run(Thread.java:841)

    • I had the same issue, I downgraded my gradle so that now it looks like this:

      dependencies {
      compile fileTree(dir: ‘libs’, include: [‘*.jar’])
      compile ‘com.android.support:appcompat-v7:23.0.1’
      compile ‘com.android.support:design:23.0.1’
      }

      And now it works.

  • nirav patel

    hi ravi,

    private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new OneFragment(), “ONE”);
    adapter.addFrag(new TwoFragment(), “TWO”);
    adapter.addFrag(new ThreeFragment(), “THREE”);
    viewPager.setAdapter(adapter);
    }

    new OneFragment() red line error show
    ———————————————————————————–

    F:AndroidAndroid-workMaterialDesignDemoTabSwipperappsrcmainjavacomprojecttabswipperactivityCustomViewIconTextTabsActivity.java
    Error:(75, 16) error: method addFrag in class CustomViewIconTextTabsActivity.ViewPagerAdapter cannot be applied to given types;
    required: Fragment,String
    found: OneFragment,String
    –> reason: actual argument OneFragment cannot be converted to Fragment by method invocation conversion

    • Ahmed Alkibsi

      Thx for lesson was help me .
      in my project i apple Text and
      Icon I use six icon .. But the sliding of tab and pager is in same
      direction( Right to Left ) I used the Arabic languges and sliding of tab
      is get wrong in slidig is not connected with pager correctly.
      >>pleas help me

    • bhavik gujarati

      Use

      android.support.v4.app.Fragment;

  • Viveka Patel

    Hello Ravi !
    Its so awesome tutorial.

    Can you tell me how to change NAVIGATION ICON default is white three lines i just change as orange color.

    and my second question is when navigation item selected,how to change drawer item text color and row background color..

    Help me i tried a lot..

  • saeed

    How can i change color of tab bottom line

    • Riley MacDonald

      You need to change the YOUR COLOR HERE line in the colors.xml

  • Damien Duflot

    Hello,

    Can we delete the toolbar and put the top bar and Fixed tab bar pinned to top ?

    Sorry for my English

    DAMIEN

  • Neeraj Kumar

    Hello Ravi Iam getting this error

    Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:assembleDebug]
    :app:preBuild UP-TO-DATE
    :app:preDebugBuild UP-TO-DATE
    :app:checkDebugManifest
    :app:preReleaseBuild UP-TO-DATE
    :app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
    :app:prepareComAndroidSupportDesign2301Library UP-TO-DATE
    :app:prepareComAndroidSupportSupportV42301Library UP-TO-DATE
    :app:prepareDebugDependencies
    :app:compileDebugAidl UP-TO-DATE
    :app:compileDebugRenderscript UP-TO-DATE
    :app:generateDebugBuildConfig UP-TO-DATE
    :app:generateDebugAssets UP-TO-DATE
    :app:mergeDebugAssets UP-TO-DATE
    :app:generateDebugResValues UP-TO-DATE
    :app:generateDebugResources UP-TO-DATE
    :app:mergeDebugResources UP-TO-DATE
    :app:processDebugManifest UP-TO-DATE
    :app:processDebugResources UP-TO-DATE
    :app:generateDebugSources UP-TO-DATE
    :app:preDebugAndroidTestBuild UP-TO-DATE
    :app:prepareDebugAndroidTestDependencies
    :app:compileDebugAndroidTestAidl UP-TO-DATE
    :app:processDebugAndroidTestManifest UP-TO-DATE
    :app:compileDebugAndroidTestRenderscript UP-TO-DATE
    :app:generateDebugAndroidTestBuildConfig UP-TO-DATE
    :app:generateDebugAndroidTestAssets UP-TO-DATE
    :app:mergeDebugAndroidTestAssets UP-TO-DATE
    :app:generateDebugAndroidTestResValues UP-TO-DATE
    :app:generateDebugAndroidTestResources UP-TO-DATE
    :app:mergeDebugAndroidTestResources UP-TO-DATE
    :app:processDebugAndroidTestResources UP-TO-DATE
    :app:generateDebugAndroidTestSources UP-TO-DATE
    :app:processDebugJavaRes UP-TO-DATE
    :app:compileDebugJavaWithJavac
    E:AndroidProjectsTabsappsrcmainjavacomneerajreachtabsMainActivity.java
    Error:(30, 50) error: cannot find symbol variable viewPager
    Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’.
    > Compilation failed; see the compiler error output for details.
    Information:BUILD FAILED
    Information:Total time: 3.067 secs
    Information:2 errors
    Information:0 warnings
    Information:See complete output in console

  • Gabriel Fernando Manuel

    Thanks For this Tutorial very nice, i was sofring because i had this implementetion using Actionbar..Thanks Man

  • Gabriel Fernando Manuel

    Sorry for my Englesh

  • Deven Singh

    Hi Ravi, First of all Its always been very informative to read your posts, thank you for all your posts.
    Could you give me any idea to make counter badge on tabs like in whatsApp(count of how many person msg me)…thanks in advance

    • Deven Singh

      I managed to make counter badge with the hint of custom view as you wrote above. thanks…
      Happy Learning 🙂

  • anonymous

    Wow, this article is excellent! Very clean code (better than others I’ve found for this), and very clear descriptions, screenshots, and even a video. I was going to suggest including the full source code — but then I found this at the top of the page! Would suggest linking to it again at the bottom of the article (for those of us who didn’t see it immediately).

  • Eva Li

    Hello,
    How can we make tabs of tablayout clickable on pre-lollipop devices??

    Thanks in advance

  • Deepak Sharma

    Hi,

    When I implement above code by making activity as fragment then Fragments One Two and Three are not initiated second time. Can you please suggest me ?

    public class MainActivity extends Fragment {

    private TabLayout tabLayout;
    private ViewPager viewPager;

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

    View view = inflater.inflate(R.layout.fragment_hopital_tab_layout, container, false);

    viewPager = (ViewPager)view. findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout)view. findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    return view;
    }

    private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());

    adapter.addFragment(new OneFragment(), “ONE”);
    adapter.addFragment(new TwoFragment(), “TWO”);
    adapter.addFragment(new ThreeFragment(), “THREE”);

    viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List mFragmentList = new ArrayList();
    private final List mFragmentTitleList = new ArrayList();

    public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
    }

    @Override
    public Fragment getItem(int position) {
    return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
    return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
    }
    }

    }

    • Vader

      Change
      import android.support.v4.app.FragmentPagerAdapter;
      to
      import android.support.v4.app.FragmentStatePagerAdapter;

      and then extend from FragmentStatePagerAdapter:
      class ViewPagerAdapter extends FragmentStatePagerAdapter

  • Mitali Tiwari

    hello!! i cant add the ViewPagerAdapter in my code..

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

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    whenever i tried to start the app it gets crashed and unfortunately stopped… plz help

    • Abhigyan sen

      Did you add ViewPagerAdapter inner class properly ?

  • Shiza Tariq

    can i move the tabs to the bottom of the screen? anyone has an idea how?

  • jhansi laxmi

    Hi Ravi,
    Really nice tutorial,
    Back button Onclick code ekkada rasaru meeru?

    • If you mean toolbar back arrow navigation, you have to mention the parent activity in AndroidManifest.xml file. Download the code and verify manifest file.

  • cool alien

    nyc tutorial bt please tell how to call activity in each tab …please post guide..newbie here

    • We don’t use activities inside tabs. We use Fragments instead.

      • cool alien

        for that what i have to do ?………….i want to show list of songs in first tab den in second tab albums etc….how can i solve this through fragment ?………….also if i’m calling activity of song list and play in fragment (first tab)..it load bt in full screen (hides main activity..though playing songs etc working …it just not setting up in tab ) ..any solution ?

  • Pavan Kusuma

    Hey Ravi, Greetings! awesome tutorial n helpful,

    My doubt goes here. I implemented mulitple tabs with app:tabMode=”scrollable”. Every tab(fragment) has data to load which is fetched from the server. As i navigate through the tabs and when i click the previous tab, the data is getting loaded again which is fetched from server. I feel when i navigate to specific tab for the second time, the tab is getting refreshed and is loaded again. I just wanted it to stay as is without getting reloaded. Pls guide me on this.

  • Neon Warge

    I dont understand the app:layout_behavior, what magic did you cast to make it appear as such?

    • Its android’s inbuilt property introduced in design support library.

  • ragha

    do we have to create a separate file for adding the library

  • Sinem Elmacı

    hi ravi,
    thank you and i wanna ask you something;
    how can i set TextView in fragment_one or fragment_two by programmatical?

  • Howard Oi

    how can i set the colour change when the tab is select and change image too?

  • Raghav Satyadev

    Hi ravi can I move these tabs to bottom or after any other layout

    I want some layouts between toolbar and tabs please reply fast

  • Junior Frogie

    Hi, how to set size for icon in tab?

  • Vishnu Palanivel

    Hi Ravi How to hide back arrow ? Simple_tab view in action bar left side.

    Sir please reply me

    • andreiancua

      Delete this line from MainActivity:

      getSupportActionBar().setDisplayHomeAsUpEnabled()

  • Suresh Babu

    hey thnk u for this article …this helped me a lot …keep posting ..cheers 🙂

  • Shudhan

    Awesome tutorial ,Thank you.

  • MartínSerrano

    Hello Ravi awesome tutorial.
    I have a problem, I implement a ListView inside a fragment but the last element when scrolling down is not showing correctly.
    Please help me with this issue.

    The details are in the next link from the StackOverflow question.
    http://stackoverflow.com/questions/34663756/why-my-listview-in-swiperefreshlayout-dont-show-the-last-element-on-android/34664873?noredirect=1#comment57109424_34664873

  • Kedar Kalkote

    When i click on one tab the adjacent tab loaded into memory but i want only selected should load how can i do this ??

    • Java Tutorials

      Have you got the solution @kalkotekedar:disqus ?

      • zzz

        viewPager.setOffscreenPageLimit(int numberOfAdjacentTabsToLoad)

      • Kedar Kalkote

        No not yet 🙁

  • Java Tutorials

    Facing same problem as @kalkotekedar:disqus . Please help us. @ravi8x:disqus

  • Paçaro

    This was great.

  • akshay_T20_bhatia

    Great Job!
    The site has a nice and clean interface too. Loved the experience. Quick and smooth!
    Thanks! 🙂

  • Trey Rosius

    Tab bar is completely white on android 5 devices…any ideas

    • What is happening when you run the sample I have provided.

      • Trey Rosius

        When i run it on android 4.4.2, it displays perfectly.But on Android 5.0 , the tab bar doesn’t adopt the default accent color(its completely white and you can barely see the tab icons) and also, the FAB button takes a different color.But this doesn’t happen on android 4.4.2

        • What is the design support library version you are using in build.gradle?

          • Trey Rosius

            23.0.1

          • Trey Rosius

            I’ve updated to 23.1.1 and its working perfectly now, i really wonder why 23.0.1 didn’t work…..Thanks for the hint…Thank You

          • Ok. Yeah sometimes it happens.

  • Sait Sami Kocataş

    it is a fresh and good tutorial i liked it

  • Mohit Mathur

    I want to put a button at the bottom of the fragment but that button is getting hidden by the default navigation bar of android. Can anybody help what to do?

  • Dave Emactao

    Hello Ravi, Can you tell me how to put Google maps on one of the tab?

    • I can’t write the code now. If you have tried, please give me the code. I’ll check.

      • Dave Emactao

        Thank you for Replying Ravi. What I Actually what did was I created a new fragment that inflates my map xml file. Is there a way I can modify the map through the Fragment?

  • Pratik Chandra Shukla

    Its Very helpfull, tysm….

  • Jovie Brett Bardoles

    Hi Ravi, do you know how to change text color of the tabs? I got black colored texts after implementing the tabs.

  • Lalit pratap singh

    tab icon is not coming on left of the title

  • Oscar

    Hi,

    How do i get rid of the title bar? I want my app to just show the tabs.

    This is great stuff.

    Thanks!

    • You can remove the android.support.v7.widget.Toolbar layout from both the xml and activity class.

      • Sheetal

        hi i have problem… my app runnig well connected to gcm and get push notification… but when app is closed and tapping on notification … itt not see on main activity

  • sunny DEOL

    hello,
    how can we trigger a particular fragment on click the tab because it show all the fragment only once
    but when we click like tab 1 then it does not restart that fragment.
    How can we resolve it ?

    Thanks !

  • Kwan_Gfriend

    How can i put recycle view in this fragment, i want to put recycle listview in one fragment. Thank you so much for teaching many lesson

    • Just like fragment. Keep all the onCreate() into onCreateVeiw() of fragment

      • Kwan_Gfriend

        Thank you so much.. You are my teacher… I read all of this website… Thank you so much

  • Oscar

    Dumb question, im still learning developing, but do contents go into Tabs java, or main activity java?

  • Sefin Francis

    how to implement in this tabs json data

  • Danish sharma

    learned two things today navigation drawer & tabs layout in material design, but i have one doubt in navigation drawer one icon with three parallel lines is created automatically & in this tutorial arrow icon is generated, but you don’t have taken any image then how it is generating automatically ?

  • gal

    Thank you very much!!
    why i is my layout is empty?

  • Simis

    Hi , Thank you for this tutorial.
    Can you teach me how can i settext of any textview in fragment from MainActivity or call a subroutine in fragment ?
    i tryed this :

    oneFragment = (OneFragment) this.getSupportFragmentManager().findFragmentById(R.id.fragment_one);

    but this give me NullPointerException error

  • Anthony

    When swiping/scrolling across the tabs its not loading in the correct order please help us solve this
    for example when i swipe to tab2 it will load tab3 and such.
    please help fix this
    otherwise the code works perfectly

  • Jay John Chiong

    I tried the code and I my tabs only has ICONS in it but it is way too small..why?

  • MartínSerrano

    Hello everyone, somebody already trying to change the icon when tab is selected. I try to change the icon when current tab is selected, but I don´t know how is the correct way to do it?.

    • Anwar Samir

      tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

      @Override

      public void onTabSelected(TabLayout.Tab tab) {

      if(tab.getPosition()==0)

      {

      tab.setIcon(R.mipmap.ic_action_add);

      }else

      {

      tab.setIcon(R.mipmap.ic_action_lab);

      }

      }

      @Override

      public void onTabUnselected(TabLayout.Tab tab) {

      if(tab.getPosition()==0)

      {

      tab.setIcon(R.drawable.ic_menu);

      }else

      {

      tab.setIcon(R.drawable.ic_menu);

      }

      }

      @Override

      public void onTabReselected(TabLayout.Tab tab) {

      }

      });

      try this code inside your activity
      and it will work

      • 陈铭卓

        Hi Ravi, Thank You for this tutorial.
        If I open app is not all the onStart method and the onResume method of the fragments will be called at the same time?
        But I want to choose which tab to call again.

  • kavach chandra

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.support.design.widget.TabLayout$Tab android.support.design.widget.TabLayout.getTabAt(int)’ on a null object reference

    App crashes with this error when i try to use the setUpIcons functions that you’ve mentioned above.
    Please help.

  • Vanraj Vyas

    Hi Ravi, Thank You for this tutorial. I just want to add some more functionality like on swipe change title and action item. by following your tutorial how i can change the title and action item on sipe can you help me? Thank You in Advance.

    • I guess swipe is already working right ?

      • Vanraj Vyas

        yes its work. i just want to change Titles on swipe.

        • You can use tab listener for this or viewpager listener. On the change of viewpager, set the tab a tile.

          I didn’t have code ready with me. But it something like getTab() at index and setText()

          • Vanraj Vyas

            Thanks Ravi, It Works i used viewpager listener with public void onPageSelected(int position)

          • Good 🙂

      • Vanraj Vyas

        and if you see in whatsapp app you can see on swipe action item change. on Calls action item app Phone icon, on chat select contact and in contacts add new contact.

  • amit srivastava

    Hi..I implemented Fixed Tabs in activity it was working fine, but I want to add Fixed Tabs inside a Fragment the same is not working as expected.
    Please someone suggest how to do this with Fragment?

    Thanks

  • Ashish Mathur

    My app works fine on lollipop but whole appbar got hidden in api 16(4.1.1).. help pls??

  • Ameya

    There is a lot of issue with nested Fragments. Suppose, you add a gridview to FragmentOne and upload images to it from gallery , once the phone is rotated the images in gridview are lost. The images are also lost when the app is re-launched and other fragments are selected.

  • Hajrieyan

    Hi, thanks for your tutorial. But why my icon always on Top? although i use first step to add icon (Left side Icon). And how to change font size?

    Thanks for help

    regards
    Hajrieyan

  • Sage Pawan

    Great tutorial Ravi. The tab layout seems to have default padding. I am trying to remove the default padding and give custom background color to tab. tabPaddingStart and tabPaddingEnd when set to -1dp is working just fine. But tabPaddingTop and tabPaddingBottom when set to -1dp wont remove the tabLayout padding. Any suggestions please?

  • dec0yable

    When i use your code in Mainactivity.java i can’t add the imports for the three fragments or R the rest of the code is exactly the same. Can you help me?

  • Ali Farhan Ansari

    hi ravi bro i’m use the same code you give but when i run my app i got an error like

    java.lang.StackOverflowError

    at android.widget.TextView.jumpDrawablesToCurrentState(TextView.java:6021)

    at android.view.ViewGroup.jumpDrawablesToCurrentState(ViewGroup.java:5740)

    at android.view.ViewGroup.jumpDrawablesToCurrentState(ViewGroup.java:5740) …….

    do you tell me what is wrong

  • Masoud jamali

    hi ravi.

    I’ve used your code.

    and it’s worked good.

    but i use persian language .in persian language tab number one tab is in right side.

    how to change alignment of tabs.

    tanx.

  • Diastowo Faryduana

    may i ask something? why the TabIcon variable type is Int not String? i’m little bit confused about that. thanks 🙂
    btw, great tutorials 🙂

  • Gaurav meghanathi

    i want to tab in page of bottom with text and image how i can set…?

    • lo Roy

      add
      android:layout_gravity=”bottom”
      in

      and move this block to the bottom of

  • Anurag Singh

    what if we want to remove that “Back Option” icon (which is on top left corner) from app?

    • Pankaj Lilan

      @disqus_vAUOTDuxot:disqus you can write getSupportActionBar().setDisplayHomeAsUpEnabled(false);

  • Ahmet Keser

    Hi Ravi,

    Instead of keeping tablayout instance on Activity class, can I apply same approach on Fragment,

    I mean there will be a one fragment and on it there will be 3 different Fragment

    is it possible?

  • DonV

    Hey..in two tabs i want to start to an activity.how to start an an activity. If i do, i can only inflate my activity layout but not activity.please help me

  • Awera Suk

    This tutorial work fine for static pages. How about if i want to change the view. If i have 4 tabs and 3 of them are displayed and one will be called on the action taken from the 3 tabs. When u implemented drawer u used frame_container to replace the fragments with fragment transaction. How to replace the view pager to replace it with new fragment.

    I have tried this and it is not working. That is why I am asking

    FragmentTransaction trans = getActivity().getSupportFragmentManager().beginTransaction();
    trans.replace(R.id.viewpager, new XYZFragment());
    trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    trans.addToBackStack(null);
    trans.commit();
    Thanks

  • Beghoura Farouk

    tabLayout.setupWithViewPager(viewPager);

    The app crach when i add this line any idea ???

    • emmarc

      I don’t know if this can help you.
      I have the same problem not long ago, but I already fixed it with checking the build.gradle file. Apparently at that time, there were an inconsistency between com.android.support:appcompat and com.android.support:design version in my build.gradle file. So I changed them both to the same version. And voila!! The code can run just fine.

      THESE LINES:
      compile ‘com.android.support:appcompat-v7:23.0.1’
      compile ‘com.android.support:design:23.0.1’

  • Nattawut Kongtan

    Hoe can I fix Missing styles. Is the correct theme chosen for this layout?
    Thank you

  • Wesley Chaves

    what to do if you want the app already open in tabs (Custom View Icon & Text) type the layout of Whatsapp?

  • Great article. Although, how would you add a DrawerLayout and NavigationView to the layout file in order to add a Navigation Drawer instead of ActionBar home button?

  • Alfian Effendi

    no errors but always force closed. help please

  • Akshay Kumar

    Hello Sir, I am using same for Icon Text Tab but in my application icon and text are not coming side by side.

    • August

      same here. did you solved it yet?

  • I am using tab Layout. By default there is always a single tab opened. But the problem is that the single tab is not taking entire tab layout width i.e. the screen width. It is fixing on the center. I have tried adding tabGravity as ‘fill’ and tabMaxWidth as ‘0dp’.

  • Joe Higashi

    Click not Working =

  • Naufal Prakoso

    I have 2 fragments and in a fragments have a different java logic. Where i am i put the java logic? When i put to the fragment, ‘cannot resolve method findViewById”, “Cannont resolve method getApplicationContext”

  • Simar

    How to change the Text Colors in the Tabs ?

  • hi, thanks for making a post on this topic, I don’t the text to remain capital, I have defined a custom style for that purpose, but still its not helping. What can be done?

    • Can you give me the code you defined in the styles?

  • Nishu sharma

    hello ravi sir,

    i am getting compile time error at line-13 in MainActivity.java

    error – cannot resolve method ‘setupViewPager(android.support.v4.view.ViewPager)’

    any idea whats wrong??

    sorry, its resolved, how can i delete this comment 😛

    and many many thanks to you Dear Ravi 🙂

  • Nishu sharma

    just one question, why you used CharSequence instead of String ??

  • Suraj Bobade

    Hey, I have created one app, and now want to integrate two of activities in single tabbed activity.
    How to do that?

  • Inzimam Tariq

    I started with the same instructions and its working at the 1st level, implementing Material Design to the toolbar But when I added fragments and their code app crashes and does not show anything. What to do now ?

    • Check the LogCat for errors.

      • Rick

        @ravi8x:disqus Can you make a tutorial of a simple TextView displaying anything but compatible with every version of Android starting from 2.2, 2.3.3 and so on?? I don’t think it will take much of your time, so it would be nice if you do that ASAP. Thanks.

      • amaterasu07

        Hello. How do you handle the back button press on the left of the tabs?

  • Akash shrestha

    how to increase the size of icon in tab?? please help…

    • Margot Le Rouzic

      same question. Did you solve it ? 🙂

  • Atul

    Why to select “Blank Activity” and add tabs afterwards when it gives option “Tabbed Activity” itself ?

  • Rick

    @ravi8x:disqus Can you make a tutorial of a simple TextView displaying anything but compatible with every version of Android starting from 2.2, 2.3.3 and so on?? I don’t think it will take much of your time, so it would be nice if you do that ASAP.

  • User X

    FATAL EXCEPTION: main
    Process: com.example.curiousapps.ahtabs, PID: 16262
    java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v7/internal/widget/TintManager;

    On this line => tabLayout.setupWithViewPager(viewPager);

    Why is this error appearing? I get stucked in step 12.

    • Make sure your gradle is like this:

      dependencies {
      compile fileTree(dir: ‘libs’, include: [‘*.jar’])
      compile ‘com.android.support:appcompat-v7:23.0.1’
      compile ‘com.android.support:design:23.0.1’
      }

  • Jovie Brett Bardoles

    Hey man, do you know how to change the font of the tab texts?

  • Luthfi M Nabil

    Works Nicely..

    Thanks 🙂

  • goxx00

    Hey 🙂 i have a problem while step 12.

    This is my error-code:
    java.lang.NoSuchFieldError: No static field AppCompatTheme of type [I in class Landroid/support/v7/appcompat/R$styleable; or its superclasses (declaration of ‘android.support.v7.appcompat.R$styleable’ appears in /data/data/com.example.gcp8fe.myapplication/files/instant-run/dex/slice-slice_2-classes.dex)

    i hope you can help me. 🙂

    • Rick

      have you rebuild the gradle first before run the app?
      these are my settings:
      compileSdkVersion 23
      buildToolsVersion “23.0.1”

      dependencies {
      compile fileTree(dir: ‘libs’, include: [‘*.jar’])
      compile ‘com.android.support:appcompat-v7:23.0.1’
      compile ‘com.android.support:design:23.0.1’
      }

      My suggestion is to build the gradle first after fixing your build.gradle file.

  • User X

    Hey Ravi, I’m making a module based on this example, but I realized that my viewpager doesn’t change the fragment when I change the selected Tab. Why in this example the change happens without setting manually which fragment must be shown?

  • kaushal

    Hi….can we set different background colors for each tab…is it possible

  • Tasmia Rahman

    Can you please do a tutorial on this : https://raw.githubusercontent.com/roughike/BottomBar/master/demo_shifting.gif
    and explain the codes along with it?

  • imma_newbie

    i would like to know how can i modify the back button on the toolbar?

    • George

      you have to delete this line in the OnCreate method in main activity … getSupportActionBar().setDisplayHomeAsUpEnabled(true);

  • Druckerschwaerze

    thank you!!

  • sasi

    Hi Ravi,
    Thanks for the gud tutorial, the code is working fine but i want to connect to bluetooth automatically when i click/scroll to another tab. can u pls help.
    Can u pls let me know how to add onclick listner to the tabs.. or is it possible to add onclicklistener…. or is there another way to perform the same…

  • Morteza Rohani

    hi Ravi
    thanks for androidHive
    1. how can i load viewPager and Frangment contents with a Data Base connection By ID?

  • pradeepkumar reddy

    how to increase the size of text in tab

    • Margot Le Rouzic

      same question. did you solve it ? 🙂

  • pradeepkumar reddy

    how to make the text in tabs as bold

  • Joan

    Hello! I want to loading data from internet when you swipe to fragment 1, and when you go to the fragment 2 this have to loading data from another page. I don’t want to loading everything when the activity start. How can i do thtat?

  • Ramesh Bista

    Thanks for the simple and clear tutorial

  • shashi patil

    hi ravi…
    how to send data between tabs?? like we do with activities by using intents… please share code for that

    • Alexiz Hernandez

      What type of data are you wanting to share between the tabs?

      • shashi patil

        string

  • Alexiz Hernandez

    I don’t seem to be able to even start this tutorial since my Blank Activity contains a “content_main.xml” file. You never mention this file in the tutorial and when I start the styling process, I get tons of errors.

  • Vadivel C

    hi This is vadivel chinnasamy,i implement TabLayout with Custom icon ,But i not able to change icon selected tab icon.is it possible in TabLayout

  • Vadivel C

    i implement tablayout with Icon ,But i’n not able to change Icon for selected tab,

  • Alan

    Thanks for great tutorial. I’m using a Navigation Drawer with fragments. I need only one fragment with tabs. How can I achieve that? Is there a way to hide tabs?

  • Bruno Chichava

    Great tutorial, congrats!

  • Marlon Arteaga Morales

    help me please someone. I need to change this colors of letters please!!!

  • Gayan

    is is possible to add floating Button inside the fragment? how can i do it? anyway, this was very helpful to beginning.

  • Marco Di Iorio

    hi guys, if i put a list view with checkbox in a view pager and another list view with checkbox in another view pager, if i check a checkbox and click on another tab and after i comeback to previous tab, the checkbox before selected now is not selected….why?

    • Fragments will be recreated when you view them again. You need to store the checkbox state somewhere.

      • Marco Di Iorio

        How can i store checkbox selecred?

        • reza k

          one way is using (shared preference) in android to store a variable. I have a tutorial video for this. you can Email me if want it. mrk.mp74@gmail.com

  • Dario

    Hi!, what’s the problem if use more than 3 tabs, in my aplications i want four or ten tabs but in many tutorials there programer 3 at most

  • Shiam

    How to run that back arrow on top left?

  • Jyothi Ch

    Using list view in tabs is strucking its not scrolling upwards.
    Please help me to get out of this.

  • Kogwar Riskadh

    Hi guys! Is it possible to create a tab-layout as such within a fragment or is it limited to activities? What I want to achieve is a second tab layout on the bottom when selecting the third tab as in the first example. Is this even possible…?

  • BASIT QADRI

    Can i customize the back button which is on toolbar I need a navigation drawer instead

  • Sohan Kumar

    hi!! my app crashes on this line of code

    tabLayout.setupWithViewPager(viewPager);

    can u help ?

  • ARASHI Funsho

    My app crashes when i try to show progress dialog in any fragment more than once. pDialog.show() results in a nullPointerException the second time. From stackoverflow I heard it has to do with something like fragment instance bla bla…. but I can’t seem to wrap my head around that. Please help

  • maziyar

    hi, it was a very usefull project, i have a question: in scrollable tabs, how do you set fragment four to be selected and in the front? not first, but in the front. thank you.

  • TimeTraveler

    Amazing work…fantastic Tutorial 🙂 as usual great code RAVI, Very useful.Thx

  • Carlos Aurélio

    In fragment_one.xml I use floatingactionbutton layout_gravity=”bottom|end” but my app cut information from this button how to solve?

  • swapnil jadhav

    How to disable specific tab

  • August

    hi Ravi! thanks for your awesome tutorial. 1 question: how to combine this tutorial with your other tutorial on drawer http://www.androidhive.info/2015/04/android-getting-started-with-material-design/ ? I want to make it for every item in drawer, have 2 tabs. already successfully tried both of these tutorial but now to combine them.

  • Hilal Özdemir

    Thank you for the good explanation, after searching many tab usage, finally yours worked without error, but i need to fill tabs with information now, how can i do this? for tab one a list of content named Beginner, for tab two another list named Intermediate?? can you help me?

    • Vernon Clive Kawonza

      My two-cents would be to put that information population code in the fragments for each respective tab

  • Gon Her

    I like to call another adapter?

  • Pradeep K C

    tab layout is not working on jellybeans device. please help

  • BSAAuthority

    Hay dear kindly provide:
    import info.androidhive.materialtabs.R;

  • Grégoire Meylan

    Hi,
    Thanks a lot for this tutorial. I was struggling with this concept… It’s clear and simple. I understand fragments better now.

  • Bilal Saeed

    i Ravi, Its so awesome tutorial. Can you tell me how to change color icon, text color when icon tabs selected (CustomViewIconTextTabsActivity)..?

  • Abhinav Soni

    add fragment function not working…only adding one fragment…..

    public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
    }

    argument in this change to particular fragment always

  • Rajdeep Singh

    thanks very much

  • Umut Dönmez

    thank u so much for tutorial 😀

  • Shujhal Singh

    sir, if i am call webservice in 1st tab then 2nd tabs web service also call
    how to do that if i m click 1st tab the webservice or 1st tab page call only not other
    plz help me

    • sandeep

      same problem here… 🙁

    • Amer Shaker Al Othman

      Each Tap extends Fragment so it has its own View … it works well with me
      This is my Code Fetch Products is a Class for fetching product from the webservice

      public class Tap1 extends Fragment {

      private static final String oral_surgery_URL=”http://gp.comli.com/web%20services/apphome.php”;

      @Override
      public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      View view=inflater.inflate(R.layout.content_tap1,container,false);
      new FetchProducts().gettingProductsFromWebService(view,oral_surgery_URL,”home”);
      return view;
      }
      }

  • Amit Verma

    Hi Ravi Sir, I am adding this tab layout with the navigation drawer, but when I am going from DrawerListItem to HomeFragment my Fragment Tab not showing any data , plz help me thanks alot

    • Amer Shaker Al Othman

      1- Make a new activity to be a Fragment container for the drawer items
      2- on the onNavigationItemSelected method taype
      YourFragment fragment=new YourFragment();
      categoryName(fragment,”Prosthodontics”);
      and use this method
      public void categoryName(Fragment fragment,String title){
      Intent intent = new Intent(this,ProductCategories.class);
      intent.putExtra(“fragment”, (Serializable) fragment);
      intent.putExtra(“title”,title);
      startActivity(intent);
      }
      3- On the activity that you have created put this code on the onCreate method
      Intent intent = getIntent();
      setTitle(intent.getStringExtra(“title”));
      fragmentTransaction((Fragment) intent.getSerializableExtra(“fragment”));

      and also use this method

      public void fragmentTransaction(Fragment fragment){
      FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
      fragmentTransaction.replace(R.id.fragment_container, fragment);
      fragmentTransaction.commit();
      }

  • Mohit Mathur

    When i am trying the same code in Samsung tab. The icon only layout is putting the icons to the end of the layout, means i have two tabs with only icons , when i install the app on tablet the left tab icon shift to right and right tab icon shift to left. Why it is happening like that??

  • Habib Olou

    Thanks for the tutorial, Please how do i switch or move from one fragment to another when a button is clicked. I have tried but i am having a problem with the fragment ID(container). Please help me.

  • Vir Bhatt

    Hello Ravi sir,
    I like your all code. You don’t know but you help me many times. I want to ask one doubt that in TabLayout I want to develop that when user reached at last tab and he/she swipe on left side then again it should show the first tab. It means it should work like non stop swipe TabLayout. Is it possible? Please help me.

  • Paras Arya

    These codes are great. I added ChartView to these tabs for my app. Now whenever I change tabs, the chartviews disappear. I searched online and discovered that the problem is with using “getSupportFragmentManager()” instead of “getChildFragmentManager”. But “getChildFragmentManager()” is of “Fragment” Class and here, “FragmentActivity” Class is used. Can anyone please help me out on this. Have a project to be submitted within the next week.

  • Mahesh Mohan

    How to refresh or recreate the 2 d fragment on button click from activity.

  • Corvo Feng

    Nice !!

  • Franklin Joney

    How to change text and icon color as i wish when tab or viewpager select

  • Parth Vora

    i want to set the icons to the left of the text in tablayout but not working with the above code.

  • #Ravi……. I want to add Pinch Zoom function in every Fragment pages for images . plz Help

  • junaid

    when i click on tabs titles not working nor toolbar…please help me

  • Manish Shakya

    In Android kitkat

    FATAL EXCEPTION: main
    Process: package_name, PID: 5287
    java.lang.NoClassDefFoundError: com.navinfotech.activity.fragment.TabFragment1
    at com.navinfotech.activity.MainActivity.setupViewPager(MainActivity.java:73)
    at com.navinfotech.activity.MainActivity.onCreate(MainActivity.java:58)

  • Marco

    I have a problem using tab layout: i have 3 columns, and i want an indipendent fragment list for each tabs in the fragment manager), so i can add and remove independently in each columns…How can i manage it? (i’ve made fragment using recycle view)

  • gordon

    hello
    if i change value in the textview is error.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
    textview=(TextView)container.findViewById(R.id.textViewFragment1);
    textview.setText(“hello”);
    return inflater.inflate(R.layout.fragment_one, container, false);
    }

    How do I change the value in the Textview?

    • gordon

      solution :

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
      {
      View v = inflater.inflate(R.layout.fragment_one, container, false);

      textview=(TextView)container.findViewById(R.id.textViewFragment1);
      textview.setText(“hello”);

      return v ;
      }

  • Mahesh Ramuni

    Sir please tell us how to play youtube videos in fragments of tab layout

  • Sunny Chaudhari

    hey, i want to hide my toolbar when i scroll on my fragment. what should i do?

  • Mandar Wadkute

    hey guyzz, i’m getting a small thins wrong, when i scroll, the toolbar(actionbar) is not hidding. please tell me, what can i do?

  • Jack

    Good tutorial!
    If you strive to create an application with unusual looks and navigation, you are welcome to use the LoopBar library. It’s really easy to integrate and can add spice to any app! https://github.com/Cleveroad/LoopBar

  • Faizan Shaikh

    Hello Everyone!
    I am new in Android development,
    I have 3 Tabs, each of them contains different layouts with a button, THE ONLY FIRST TAB is TURNING ON & OFF THE FLASHLIGHT with changing the text, But when i switch to the next/another TAB that TAB’S button only changes the text but not TURNING OFF & ON the FLASHLIGHT. I have use the switches to return all 3 tabs Fragments. Who ever the tab, is on the case 0: can use the flashlight. Can anyone help me in this please??

  • Rutul Mehta

    How to add dynamic fragment in app ??

  • Rocky Papu

    hi…help me

    i want to add more tabs with scrollable tabs i tryed it but all the tabs are getting jumbled in one layout it self me help me out with this my email is : rockypapu143@gmail.com

  • Tuấn Phạm Hoàng

    if I want to hide/show imageview when tab is clicked. How can I do it? Thanks

  • Gaurav Singh

    how can I add tabs using loop?

  • Mansoor Jafari

    Hi
    how to refresh fragment after change tab.
    for example call OnCreateView again.

    please help me.
    Thanks.Ravi

  • pradeepkumar reddy

    In tablayout, all the letters are appearing in caps. How to Make only the first letter as caps. I’m adding the fragments as
    mSectionsPagerAdapter.addFragment(new FragmentOne(), “Call”);
    mSectionsPagerAdapter.addFragment(new FragmentOne(), “Chat”);
    mSectionsPagerAdapter.addFragment(new FragmentOne(), “Info”);

  • Prathibha Nandini

    Hello Mr.@ravi8x:disqus ,
    I’ve implemented your code and it was working fine untill I’ve added Expandable listview in xml. Now it says

    ‘cannot resolve appcompat’,
    ‘expandablelistview doesn’t have a theme’,
    ‘set attributes’,
    ‘cannot resolve symbol R’
    and so many errors. I’m not able to understand what’s happening.

    I’ve tried to change dependencies to API 24, clean nd build. and many.
    But unable to resolve it 🙁
    Kindly help.

  • David Rocha

    Great tutorial! Thank YOU SO M U C H!

  • usman

    how to design fragment layout…if add a textview in fragment in show on top of screen behind tool bar…how should i fix it..???

    • Cody Coogan

      if you are using a Linear Layout add tag: orientation:”vertical”

  • John Koub

    And what about rad round badges with digits that hides and appears when it necessary.

  • Koko Rambo

    when I used tab with above icon, my app had stopped. What happened? Thanks!

  • pradeepkumar reddy

    how to create custom tabs with custom tab indicator using tab layout ?

    The following is the layout which includes tab layout

    The following is the layout for custom tab : –
    ———————————————————-

    By using the above layouts i’m getting some space on the left side of the tab indicator. How to get rid of that space ??? Here i had disabled the tab indicator by setting tab indicator height to 0 dp and i’m using custom tab indicator.

    is there a way to post the screenshot here, so that it will be easy to understand the question.

  • alex

    Why a dependency on 5.0 Lolipop and higher? Why you don’t use KitKat 4.4? KitKat covers 74% of users while Lolipop only 40%

  • Satrio Teleng Bagaskoro

    when i scroll, the toolbar(actionbar) is not hidding. please tell me, what can i do?

  • sridhar sid

    FATAL expansion! for android 6.0
    when i tried to run the app through emulator, it is showing app has stopped unfortunately, please help me with this!

  • Santi Gil

    Where is a good or conventional path to save the icon images? I mean to ic_tab_favourite, ic_tab_call, ic_tab_contacts.

    • Chris

      With icons, depending where you have downloaded them from. (I would recommend: https://design.google.com/icons/ ) You should get an either black or white icon, with mutiple sizes ie HDPI or XXHDPI. With those drag them into the folder in your project called either drawable-HDPI or mipmap-HDPI then drag the corresponding icons into the folders. Then in your code or XML files use R.drawable.icon_name or R.mipmap.icon_name to get youtr icon. Hop that helped 🙂 Chris

  • Atula

    can we hide the underline under tabs ..?

    • you apply same color as of tabs.

      • Atula

        Thanks for responding Ravi.

  • Raditya

    Nice~
    how do i change the back icon in a toolbar? or hide it?

    • Pratik

      Inside your onCreate() method remove this line
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);

  • Luis Chavarria

    Hi, with this example, how to change the fragment textview (fragment_one.xml) from main activity ?

    I tried with this code, but i have problems

    I add in MainActivity

    OneFragment Data1 = new OneFragment();
    Data1.setPhone(“8888888”);

    I add in OneFragment.java

    public void setPhone(String text){
    TextView txtPhone = (TextView) this.getView().findViewById(R.id.txtPhone);
    txtPhone.setText(text);
    }

    And I add the id textView android:id=”@+id/txtPhone in fragment_one.xml

  • sadegh

    hi
    how to change the font of tablayout ???
    and
    how to change tab right to left
    tnx

  • sadegh

    @ravi8x:disqus hi
    how to change the font of tablayout ???
    and
    how to change tab right to left
    tnx

  • Nattawut Kongtan

    How to add Cardview inside Tabs
    Thank

  • Kaushal Kishor

    i want to use same layout for all the fragments. fragments should have different content. how to do that.

    • nikiz

      did you do that? I need a solution!

  • Mahad ALi

    thanks broda

  • isara winkbad

    how to get badge in tab?

  • Atula

    I don’t want tab hint color.. like when we press a tab then a transparent type color show for short time. Can you tell me how to remove that?

    • Atula

      solved it by adding app:tabBackground=”@android:color/transparent” in xml

  • Talusani Madhuker

    @ravi8x:disqus Can you explain me how you had put those buttons and for each button you displayed different tabbed layouts . In which layout you have put buttons and how you displayed them on the button clicks?

  • Anchal Singh

    How can I change your theme into transparent theme ??

  • Amar Ilindra

    Hai,
    I tried this tutorial and I want to show icon and text in tabs. (Icon and text should be horizontally aligned). So i used the code in “4. Tabs with Icon & Text”
    but i’m getting text below the icon as shown in “6. Custom Tab View with Icon & Text”

    How can i get icon and text in single line ?
    Thanks in advance

  • Pedro Gonzalez

    Excellent tutorial! I created a Git repository following the code and everything works great:
    https://github.com/pdrogfer/TabActivityPractice

  • hey guys, i getting error with this tutorial, the error says “must implement OnFragmentInteractionListener” , what should i do? it seems like i have different android version with this tutorial, which this tutorial never implement that listener.

  • Gürkan Çatak

    Thank you for this tutorial. I used and it works but I have a question to you. How to change(increase) size of the icon(tab with only icon)?

  • Đhávãľ Sakariya

    very usefull code

  • Samar Khaled Sabateen

    It’s a great work i need to ask how can i add an icon like phone icon next to the title and change the title insted of simple tab to my own text 😊

  • Khalid Bj

    hey i download the code and there is problem with is it’s when click Movies and get back and click home it will NOT show home_fragment it’s keep movies_fragment ! why is that ?

  • Shubham

    how i put tab in bottom of layer….

  • Bocci

    How can i go BACK with left arrow? Where is this method?

    • Gsp Ivan

      u go to your manifest and define the parentActivity that u want to go to
      eg android:parentActivityName=”.App.MainActivity”>

      Also make sure u include
      getSupportActionBar().setDisplayHomeAsUpEnabled(true) in the main Activity

      hope it helps

  • numan khan

    How can i show a listview with CustomArrayAdapter on every tab?

  • Bhanu Prakash Sharma

    Hey Ravi

    i just recommended this article to everyone and this is most easiest way for teaching and giving tutorial which i ever seen.

    Good work
    Keep it Up 🙂

  • intakhab ali

    Error:(2) Error retrieving parent for item: No resource found that matches the given name ‘MyMaterialTheme.Base’.
    in getting and error

  • Boby Haryanto

    I’ve read this before. Thanks for your responses! 🙂
    The tab bar are at the top of the screen by default. Can we move it to the bottom programmatically?
    *) I’m new to this one

  • jothi prakash

    i have three fragments

    if i swipe from fragment1 to fragment2

    fragment2 oncreateview is not called ,it directly calls fragment3 oncreateview

    if i swipe from fragment3 to fragment2

    fragment1 oncreateview is called instead of fragment 2

    please help

    • These fragments will be pre created by android itself. It means when you are going from 1 – > 2, 3 will be pre fetched so that it won’t cause any delay when user comes to that tab.

      • jothi prakash

        Thank you

  • Pranav

    Hello,
    For the first time its working fine but when I got back and come to that page none of the fragments gets load.

  • prasanth s

    i couldn’t add more than one fragment in viewpager

    it shows error in new TwoFragment() and ThreeFragment() line

    private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), “ONE”);
    adapter.addFragment(new TwoFragment(), “TWO”);
    adapter.addFragment(new ThreeFragment(), “THREE”);
    viewPager.setAdapter(adapter);
    }

    • Do you have those fragments created. If yes, check for import statement of Fragment.

      Sometimes Fragment imported as .Fragment and .support.Fragment.

  • Sagar Aghara

    Hey Ravi Sir, nice tutorial but tell me one answer of my question…..nothing error was comes in this tutorial while i implemented that….but in my Tab Layout i appeared [Icons+texts] vertically By Default…then how can i set it to Horizontally…..same as in your 4th Step Screen shot….Thank u in Advance.

    • Pls post the screenshot.

    • I’ve the same problem … have you fixed it ??

      • @ravi8x:disqus

        • Sagar Aghara

          if u solve problem…thn tell me…also i will try…Thank u.

          • Upload your code somewhere I’ll look into it.

          • Sagar Aghara

            Sir its problem of Android Studio version problem..???
            i used Android Studio 1.3.2
            i cant use Latest Studio bcz of 32 bits OS.

          • I don’t think that the problem is the android studio version. I’m using the latest one (2.2.1). I don’t understand it, because the official google spec shows that the default behavior should be vertical alignment, and not horizontal https://material.google.com/components/tabs.html#tabs-specs

          • Sagar Aghara

            Sorry for late reply bro….yes i seen Tab layout default behavior is Vertical..By the way Our code is Fine….if we want to Horizontal ..than we have to make some changes.

          • Sagar Aghara

            [1] TabMainActivity.java

            package tabs;

            import android.os.Bundle;
            import android.support.design.widget.TabLayout;
            import android.support.v4.app.Fragment;
            import android.support.v4.app.FragmentManager;
            import android.support.v4.app.FragmentPagerAdapter;
            import android.support.v4.view.ViewPager;
            import android.support.v7.app.AppCompatActivity;
            import android.support.v7.widget.Toolbar;

            import com.sagar.materialdesignnew.R;

            import java.util.ArrayList;
            import java.util.List;

            public class TabMainActivity extends AppCompatActivity {

            private Toolbar toolbar;
            private TabLayout tabLayout;
            private ViewPager viewPager;
            // For Tab Icons
            private int[] tabIcons = {
            R.drawable.ic_profile,
            R.drawable.ic_tab_two,
            R.drawable.ic_tab_three,
            R.drawable.ic_tab_four,
            R.drawable.ic_tab_five,
            R.drawable.ic_tab_six,
            R.drawable.ic_tab_seven,
            R.drawable.ic_tab_eight,
            R.drawable.ic_tab_nine,
            R.drawable.ic_tab_ten
            };

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

            toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

            tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(viewPager);

            // For Setting an icons in a Tab
            setupTabIcons();
            }

            private void setupTabIcons() {
            tabLayout.getTabAt(0).setIcon(tabIcons[0]);
            tabLayout.getTabAt(1).setIcon(tabIcons[1]);
            tabLayout.getTabAt(2).setIcon(tabIcons[2]);
            tabLayout.getTabAt(3).setIcon(tabIcons[3]);
            tabLayout.getTabAt(4).setIcon(tabIcons[4]);
            tabLayout.getTabAt(5).setIcon(tabIcons[5]);
            tabLayout.getTabAt(6).setIcon(tabIcons[6]);
            tabLayout.getTabAt(7).setIcon(tabIcons[7]);
            tabLayout.getTabAt(8).setIcon(tabIcons[8]);
            tabLayout.getTabAt(9).setIcon(tabIcons[9]);
            }

            private void setupViewPager(ViewPager viewPager) {
            ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
            adapter.addFragment(new OneFragment(), “ONE”);
            adapter.addFragment(new TwoFragment(), “TWO”);
            adapter.addFragment(new ThreeFragment(), “THREE”);
            adapter.addFragment(new FourFragment(), “FOUR”);
            adapter.addFragment(new FiveFragment(), “FIVE”);
            adapter.addFragment(new SixFragment(), “SIX”);
            adapter.addFragment(new SevenFragment(), “SEVEN”);
            adapter.addFragment(new EightFragment(), “EIGHT”);
            adapter.addFragment(new NineFragment(), “NINE”);
            adapter.addFragment(new TenFragment(), “TEN”);
            viewPager.setAdapter(adapter);
            }

            class ViewPagerAdapter extends FragmentPagerAdapter {
            private final List mFragmentList = new ArrayList();
            private final List mFragmentTitleList = new ArrayList();

            public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
            }

            @Override
            public Fragment getItem(int position) {
            return mFragmentList.get(position);
            }

            @Override
            public int getCount() {
            return mFragmentList.size();
            }

            public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
            }

            @Override
            public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
            }
            }
            }

          • Sagar Aghara

            [2] tab_main_activity.xml

          • Sagar Aghara

            Also i have Total 10 Fragment Java Files + 10 Fragment xml Files…That’s it…Sir

      • Sagar Aghara

        No Aron bro. still i get that Problem…..i tried more and more but it didn’t work….now i m happy with By Default tabs… 🙂

  • Mithun Sudheendran

    Hi Ravi Sir, i am your huge fan… i was following ur Tabbed activity Tutorial. In the First Fragment i have included an Imageview which will load image from a Remote URL. The Problem is when i am going to fragment 3 or 4 or further and return back to first fragment the Image is not visible. Is there any method to know which tab i have currenlty selected or to recall the Asynctask to load image again.

    https://uploads.disquscdn.com/images/7412989cc9c33cbf640ca89cb4116529aaa0bedd606ead18bf07d27a4ecff57e.png https://uploads.disquscdn.com/images/7e25dfee5d20f14c598654f11a5803f746648325a26958d387d3bd11896fdebe.png

  • Roy Hardijaya

    very useful, thank you 🙂

  • Pratik Saluja

    Thanks a lot man !!

  • Ali Sarıgül

    Thanks a lot 🙂 How i’ll do that tabs to bottom? and vertically?

  • Shivam Dhuria

    Hey,I noticed all the tabs are in Block letters,how do I change it?

  • krishna dhas

    Hi Sir, Tab Layout using time how to hide action bar? not tab title

  • Charmi Khambhati

    hey… great work done,
    but now i want to add a listview to one of the tab…
    how can i add it with the above code ad i can not extend two classes

  • walia

    hi….great work…well done…can you give me a code for a listView….in which every list item is clickable and contain another activity..and list view also show how many items are available in clicked activity….
    like this activity…its listitems shows numbers of items that they have

    https://uploads.disquscdn.com/images/3ea5835e2fbd0f7a0ccaa00d81e63a860a46f3bc6e7606750de59e042ac15fb6.png

    • Charmi Khambhati

      hey,
      i want to implement similar thing, but i could not find proper solution online nor the admin is replying.
      if you get the way out, can you please share it here too.
      thank you.

  • Vaibhav Purohit

    Hello Sir,

    This method add 2 fragments on 1st time when the screen appear and when m scrolling 1st time the third fragment is load but i want only 1st fragment load 1st time and after that on scroll second 1 is load

    private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), “ONE”);
    adapter.addFragment(new TwoFragment(), “TWO”);
    adapter.addFragment(new ThreeFragment(), “THREE”);
    viewPager.setAdapter(adapter);
    }

    this is logcat output when 1 screen appear

    10-18 08:25:30.201 27845-27845/info.androidhive.materialtabs D/one: one one one
    10-18 08:25:30.211 27845-27845/info.androidhive.materialtabs D/two: two two two

    this is logcat output when 1st time scroll

    10-18 08:25:30.241 27845-27845/info.androidhive.materialtabs D/FindExtension: FindExtension: before mHardwareRenderer.initialize, mSurface.isValid() = true
    10-18 08:25:42.311 27845-27845/info.androidhive.materialtabs D/three: three three three

  • Le clique

    I got error when i try this.. can you help me to solve that error

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.mani.authentication2, PID: 4376
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mani.authentication2/com.example.mani.authentication2.MainActivity}: android.view.InflateException: Binary XML file line #34: Could not inflate Behavior subclass android.support.design.widget.appbar
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: android.view.InflateException: Binary XML file line #34: Could not inflate Behavior subclass android.support.design.widget.appbar
    at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.example.mani.authentication2.MainActivity.onCreate(MainActivity.java:24)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.RuntimeException: Could not inflate Behavior subclass android.support.design.widget.appbar
    at android.support.design.widget.CoordinatorLayout.parseBehavior(CoordinatorLayout.java:601)
    at android.support.design.widget.CoordinatorLayout$LayoutParams.(CoordinatorLayout.java:2540)
    at android.support.design.widget.CoordinatorLayout.generateLayoutParams(CoordinatorLayout.java:1601)
    at android.support.design.widget.CoordinatorLayout.generateLayoutParams(CoordinatorLayout.java:106)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:837)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.example.mani.authentication2.MainActivity.onCreate(MainActivity.java:24)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.ClassNotFoundException: android.support.design.widget.appbar
    at java.lang.Class.classForName(Native Method)
    at java.lang.Class.forName(Class.java:324)
    at android.support.design.widget.CoordinatorLayout.parseBehavior(CoordinatorLayout.java:593)
    at android.support.design.widget.CoordinatorLayout$LayoutParams.(CoordinatorLayout.java:2540)
    at android.support.design.widget.CoordinatorLayout.generateLayoutParams(CoordinatorLayout.java:1601)
    at android.support.design.widget.CoordinatorLayout.generateLayoutParams(CoordinatorLayout.java:106)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:837)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.example.mani.authentication2.MainActivity.onCreate(MainActivity.java:24)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.ClassNotFoundException: Didn’t find class “android.support.design.widget.appbar” on path: DexPathList[[zip file “/data/app/com.example.mani.authentication2-1/base.apk”],nativeLibraryDirectories=[/data/app/com.example.mani.authentication2-1/lib/x86, /vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at java.lang.Class.classForName(Native Method)
    at java.lang.Class.forName(Class.java:324)
    at android.support.design.widget.CoordinatorLayout.parseBehavior(CoordinatorLayout.java:593)
    at android.support.design.widget.CoordinatorLayout$LayoutParams.(CoordinatorLayout.java:2540)
    at android.support.design.widget.CoordinatorLayout.generateLayoutParams(CoordinatorLayout.java:1601)
    at android.support.design.widget.CoordinatorLayout.generateLayoutParams(CoordinatorLayout.java:106)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:837)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
    at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.example.mani.authentication2.MainActivity.onCreate(MainActivity.java:24)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Suppressed: java.lang.ClassNotFoundException: Didn’t find class “android.support.design.widget.appbar” on path: DexPathList[[dex file “/data/data/com.example.mani.authentication2/files/instant-run/dex/slice-support-annotations-24.2.1_3168a2b5f1d25af44ed674ee9537cec80c294e8b-classes.dex”, dex file “/data/data/com.example.mani.authentication2/files/instant-run/dex/slice-slice_9-classes.dex”,

  • Johnny
    • delilah

      because it’s inside the package name he used. You should use your package name

    • marty45

      Use “com.example.myapplication.R” “com.example.myapplication.OneFragment” “com.example.myapplication.ThreeFragment” “com.example.myapplication.TwoFragment”, this is your package name.

  • Rulli Wuji Wijianto

    Hi, How can I implement json volley request using tabbed activity?

  • Ahmed Dusmatov

    Thanks!

  • Krishna Ch

    i am Getting these errors and app is crashing

    java.lang.RuntimeException: Unable to start activity ComponentInfo{co.checkon.corporate/co.checkon.corporate.TabsActivity}: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView

  • Kostas St

    I’m getting this error “FATAL EXCEPTION: main java.lang.RuntimeException: must implement OnFragmentInteractionListener”. Can anybode help me?

    • Shantanu Sarkar

      Please make sure that your Mainactivity implements OnFragmentInteractionListener for all fragments. Something like this

      MainActivity extends AppCompatActivity implements 1Fragment.OnFragmentInteractionListener,2Fragment.OnFragmentInteractionListener,3Fragment.OnFragmentInteractionListener
      and add this method later in code

      @Override
      public void onFragmentInteraction(Uri uri) {

      }

  • Naman Jain

    Sir how can I pass an image from one tab to another tab

  • Naman Jain

    Sir I am getting an error

    Attempt to invoke virtual method ‘void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)’ on a null object reference

  • paijojr

    hi Ravi
    how to disable swipe between the tabs?thanks

  • Rizky

    can i know how change action bar when fragment changed?

  • Sanchi

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.support.design.widget.TabLayout.setupWithViewPager(android.support.v4.view.ViewPager)’ on a null object reference
    at info.androidhive.floatinglabels.Activityfood.onCreate(Activityfood.java:46)

  • Jean-Francois Messier

    Got the source code and started playing with it under Android Studio. Works great, and code is enough documented that I can use it for my own requirements. Very good article and explanations too !!!!!!

  • The tabs take space the layout below them, how to fix this? The text ONE, TWO, and THREE are not in the middle (according the layout gravity, it should) vertical of the screen, it’s a little in the low part of the layout.

  • Abdur Rafay

    Is there a way to implement this in a fragment instead of an activity?

  • RoOpAk VaRgHeSe

    Hi Ravi, How to put this TAB in the Bottom?

  • Johnny

    Hi, How to combine listview+group title to Fragment with “Android Custom ListView with Image and Text”
    http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
    Activity and Fragment are different things

  • Dwight Light

    hey man, beautiful work, just one last thing please,i’ve been googling my eyes off. could you please add a list view to that tablayout.would really appreciate it thank you

  • Olimxon Kadirov

    thanx for useful informations

  • Mimi

    Awesome tutorial! There is just one thing I cannot wrap my head around:
    I used your tutorial to create 2 tabs, A and B, now I have a button that should change fragment A to change into fragment C how would I do that?

    • mimi

      (Keeping the same tabbed layout ofcourse)

  • Abu Nayem

    Nice Tutorial sir, in my main Activity i set mViewPager.setOffscreenPageLimit(1);. it load data for tow fragment . but i want to load only for one fragment’s data at a time. how can i achive this?

  • Amandeep Grover

    Awesome Tutorial. I followed the all the process but failed to get Text and Icon same as u did in 6. Custom Tab View with Icon & Text.
    Want the same . Please suggest.
    Only icon appearing text not visible. https://uploads.disquscdn.com/images/ba14ed758f95db9c035a3467435de872e32350a91c153e51de9fd7ba19fb07b8.png

    Many Thanks.

    • Amandeep Grover

      Sorry. I Checked it was very basic issue of colour. text colour was same as background.

  • Sohan Kumar

    How can I dynamically change the text of Tab from another activity. For ex: I want to display the count of people in my listiview in the tab text.

  • Daniel López

    How can i change the color when i select a tab?

  • Code Once Think Twice

    It’s so great buddy ! From basic to advanced, nice !

  • Ananya Srivastav

    how to set up the same custom tabs with icons and text in fragment???

    • shashi patil

      got solution??

  • nikiz

    Hi Ravi!
    I only need to display information in fragments, so code in each fragment (tab) isn’t used. I use only .xml-files to display information. Thus, all my fragments are useless. Please tell me how can I fix it?
    Sorry for my English, I’m Russian.

    • Check the 12th point code. It is loading three fragments in three tabs.

      • nikiz

        Hi Ravi!
        Tell me please, can I use one fragment instead of three and in it inflate desired layout?

        • You can but the logic might differs for 3 layouts as you might not display the same data in 3 layouts. In case the layout appearance is same for all 3 view, you can do it using single fragment.

  • Aditya

    i’m getting NULL-POINTER exception tell me soon

    setupViewPager(viewPager);

  • Aditya

    can anyone tells what exactly this error.

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.aditya.wel, PID: 13334
    java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v7/internal/widget/TintManager;

  • spartan1047

    How can I collapse the toolbar when i.e someone scrolls a List inside in one the fragments?

    like this:

    http://androcode.es/wp-content/uploads/2015/10/2015-10-27-03_51_37.gif

    im put the flags in:

    But doesnt Work. Thanks.

  • Edo Firmansyah

    hi, thanks for the tutorial ^^
    by the way, how to remove the arrow icon on top left?

    • Gandhi Wibowo

      Remove this line from your activity
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);

  • Akshay Taru

    @ravi8x:disqus Thanks for Tutorial.
    I am not able to change the Text color on Tab change in “Custom Tab View with Icon & Text”, Any suggestion?

  • Rohini Deshmane

    Only swap works. How to implement click event for tabs??? addOnTabSelectedListener and setOnTabSelectedListener not working for click event.

    • You are doing something wrong, it works for me with his code.

  • shashi patil

    @ravi8x:disqus
    i have implemented this example with json successfully… now the issue is i have implemented json listview in “fragment one” which works fine… but when i swipe to the “fragment three” and come back to “fragment two” again the method from “fragment one” is getting called… whats the issue?

  • nolonger theroad

    Hi Sir Ravi
    These styles are specific to Android 5.0
    it’s another below version ?
    my app have a v4.3 .

    thank you for article .

    • No, all the designs should be supported to below versions using support library.

  • Amit Sen

    Thanks for a such a nice programming post…but i am not able to get the icon and text in same line. Its always showing in vertically manner…it means text is showing below the icon always…Help me what i missed in your brilliant tutuorial

    • What is happening when you run the project downloaded in this article?

  • Nsikak Thompson

    please how do i use different icons to indicate when the tab is selected or not. thanks

  • ebite Zion

    Hi Ravi,
    I consider your tutorials as one of the best.Thanks for what you do.I have benefited immensely from your work and would appreciate your advice on books to advance my programming knowledge in java and android(possibly by you.).Again thanks.
    Zion.

    • Hi Ebite

      Thanks for your appreciation. Sorry I haven’t studied a complete java book yet. I learned java from various sources on internet. But I started with a book by Head First.

  • AbelardoLG

    Hi Ravi,

    Thanks for your work!

    I am building an app related to questionnaires. I have 5 tabs (= 5 tests) and for each one of them there are 20 questions.

    What should I do to swipe between questions AT THE SAME TAB (= TEST)?

    For example: here two snapshots from my app (my English is not good).

    As you can see, it consists in several tabs (=tests) and questions (20 x test). When I swipe my first question, I would like to see the second question from the second test and NOT the another test (as you did in your app here mentioned).

    Is there a layout that facilitates to me this way to navigate?

    Here the question # 1 from test #1 (imagine you are seeing the test # 2):
    https://uploads.disquscdn.com/images/4ea9bb773989e71218879253294d9757fd58d5d3c390e2653bc50f26ad72eafa.png

    Following, you can see the question #20 from test #2: https://uploads.disquscdn.com/images/42f999bcbf6fa70a98bb427334ee16c5fa73179235c9bfbdc6bdfcd16dc52581.png

    Happy new year 2017 to everyone and all best!!!

    Thanks AGAIN Ravi for your tutorial, nice work! Brs.

    • Are you storing the questions in mobile database?

      • AbelardoLG

        Hi,

        Yes, finally I am going to store the questions in mobile database like SQLite.

        I am not sure in the future we are going to migrate our mobile database but at the moment yes, in mobile database.

        Brs.

        • Ok. Try using Realm database. I am not sure about your problem, it all depends the logic you are writing.

          • AbelardoLG

            Hi Ravi,

            My question here set up is not related to how to store questions but with the navigation of questions belong to the same test.

            As you can see at the pictures, I would like to show them under the same test.

            Am I explaining it well? :S

            When I do this gesture:
            https://d30y9cdsu7xlg0.cloudfront.net/png/74544-200.png

            the next question would be showed with no to change of tab.

            Best regards.

  • Shivaprakash Patil

    I referred this example, i have doubt on this. When I move from fragment 3 to 2. Initially it loads fragment 1 and than moves to fragment 2. This is not right. Please have look onto that and debug it.

  • Pradip Shenolkar

    Hi,
    Thanks for the tutorial.
    I want to add Fragments dynamically. Is it possible? If yes, how to do that?

  • Imthaz Mohammed

    Hi Sir,
    Great Tutorial, Thank u Very Much.
    when i add some widgets like (Button or TextView) to the fragmentOne.xml how can i access then in an activity.
    i just want to make changes So, how can i Initialize the Widgets in order to make changes.

  • Innocent Kithinji

    Hi Nice Tutorial But I would like to implement Instagram’s Navigation Where in Tab One I can Open Lets say A Contact And Show its Details Go to Tab 2 Chat open a Chat And Go to Tab 3 and continue But How do I accomplish this with the above Layout that you have provided

  • Anurag Hisaria

    Great article sir….Proved to be very helpful and easy to understand…Thanks a lot

  • karthik A

    Great Tutorial…. It clears all the doubts by the time we reach the end of the article…. I guess , it’s lucky day for me… Thanks again…

  • Pandian

    Hi Ravi Nice Tutorial. I need your help how to replace bottom strip line change to up arrow

  • Nuruddin Nik Mat

    Hello sir..
    Thanks for this tutorial.. ^_^v

    I need your help.. I got 2 error..

    Thanks in advance Sir..

    1. android:text=”@string/one”
    (Error:(10, 23) No resource found that matches the given name (at ‘text’ with value ‘@string/one’).)

    [—————————————————–

    ——————————————————]

    2. Cannot Run App
    (Error running app: Default Activity not found)

    [—————–

    ——————————-]

  • Snow

    yo, sweet tutorial.
    if i wanted different colors for selected and unselected tabs, any tips on how to get this done?

  • Thank you so much!

  • mallik

    I want to use this theme “@android:style/Theme.Material.Light.DarkActionBar”, with this project, It is not supporting. Help me plz

  • Abhimanyu Khatri

    how can I retrive the instance of a fragment from adapter to reuse it for making changes in the fragment after onCreate() is called

  • Benjamin Vison

    Give this man a cookie!!!!

  • Reshma Shetty

    Awesome dude 🙂

  • ToHan0510

    Nice tutorial,
    but I have a problem, when I use to open a Dialog(Fragment) in one of the Fragments the App will close directly

    without any error warnings. How I can fix that problem.

  • Technofreak

    How can I move the tablayout to the bottom of the screen? Plz provide with the solution

  • Dipanjan Biswas

    In my case its saying like ViewPagerAdapter(android.support.v4.app.FragmentManager) in ViewPager Adapter cannot be applied to(android.app.FragmentManager).

    • You need to use import android.support.v4.app.FragmentManag in all classes.

      • Ariel Kresna

        hi Ravi i need your help fastly please help me (check my comment)….

  • Troy A Gamboa

    Is it possible to place a PreferenceFragment settings page within one of the tabs in the layout? One like this?
    https://github.com/codepath/android_guides/wiki/Settings-with-PreferenceFragment

    • Troy A Gamboa

      I found the solution, instead of extending fragment, I extended PreferenceFragmentCompat

  • shafaque sattar

    Recyler view not working inside fragment. Showing No adapter attached skipping layout.

  • Aswin

    Swipe gesture in not working. Any clues

  • Soft key

    sir please help me to design a tablayout like this wiyhout using 3rd party library.

    https://uploads.disquscdn.com/images/5c3ceb7ae6f3fdec6a504fba2dfaef80298fdcd8b61524fac51cee1043e60707.gif

    • Vipin Varghese

      me to need a solution for this

      • Sumit Lakra

        Hi,
        If you haven’t found the solution for this.
        Follow these 3 easy steps:
        1. give an id to AppbarLayout say :
        android:id=”@+id/appBarLayout”
        2. remove this line from Toolbar
        android:background=”?attr/colorPrimary”
        3. Now add this code to your activity:

        AppBarLayout barLayout;
        inside OnCreate() of your activity
        barLayout = (AppBarLayout) findViewById(R.id.appBarLayout);

        //first time background when activity loads
        barLayout.setBackground(getDrawable(R.drawable.background));

        //use swipe events to change the preferred background
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        switch (position){
        case 0:
        barLayout.setBackground(getDrawable(R.drawable.background));
        break;
        case 1:
        barLayout.setBackground(getDrawable(R.drawable.background1));
        break;
        case 2:
        barLayout.setBackground(getDrawable(R.drawable.background2));
        break;
        case 3:
        barLayout.setBackground(getDrawable(R.drawable.background));
        break;
        }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
        });

        Let me know if you have any problems.
        Enjoy 🙂

    • Sumit Lakra

      See the code below if you haven’t found the desired solution.

  • Ken Malinao

    Thanks sir ravi. Very helpful tutorial for us (beginners). Do you have tutorial on a recycler view? And when an item is clicked a new activity will be created. Thank you.

  • Ariel Kresna

    Dude i’ve been followed even copied your code into my project but i got different result in icon and text tabs, the icon is in center not in left (check image below) please i need fast response
    https://uploads.disquscdn.com/images/0a7351491793c0ed18d2fc42f793b1aa807d0091824818df400b1116e98719db.png

    • Giovani Sandri

      I have the same problem!!! Ravi Help us

      • Me too facing same issue any solution?

        • kavie

          Same Problem here,Did any one solved this problem?

    • Ahmad Fitriyansah

      change this
      setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_call, 0, 0);
      to this

      setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_tab_call, 0, 0, 0);

      you could read the description of the method here:
      https://developer.android.com/reference/android/widget/TextView.html

  • naga

    I need help from you sir…
    I have already created the tabbed activity with three tabs named as tab 1, tab 2 and tab 3 like yours. I added one button in tab 1. How do we do click operation in tab 1. I want to go from tab 1 fragment to another activity like “orders” page when click the button. Please send the program?

  • Mostafa Anter

    class ViewPagerAdapter i think it will lead to memory leak

  • Dhanashri Vasaikar

    Sir please help me
    how can i create in first line two tabs and second line five tabs

  • sonali kale

    hello sir,
    i am trying this demo into fragment but in fragment it shows only 3 tabs title and other tabs title are not display .
    please help me to solve this issues.

  • Roy

    Hi author,
    How to call API when tap into the specific fragment. Looking for your feedback soon

  • Chandrasekhar Majhi

    I have used the code. It’s working very well. Thanks for this article. But I want to know that, can we use Cardview with this concept? I am waiting eagerly for your reply.

  • liauomk

    Hi sir,
    How to change Tab’s background and indicator color ?

  • Vivek Singh

    Can you tell me how to pass data between the fragment while switch because I am gettting null when i switch the Tab

    • Abner

      You need to implement interface in the fragment, call it in the parent activity and pass the variable to the
      fragment you want

  • pammy

    Thanks for this,

  • Adrian Scarlatescu

    Hi all,
    Can anyone tell me how can I remove that backward arrow <- from the left of the Tab Layout?

    • Mik

      I’m also trying to figure out the same! Let me know if you ever figure it out.

      • Adrian Scarlatescu

        Hi,
        Just comment the following line from your main activity:

        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        • Mik

          That worked! Thanks so much!

    • Eric Ase

      Hi,
      Replace this part :
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);

      with :

      getSupportActionBar().setDisplayShowHomeEnabled(false);

      If you keep the first code, it will not work.

      Regards

  • Venktesh Sakthi

    hi…I’m adding widgets dynamically in my second fragment out of 4.That tab is not refreshing every time when i change to that tab.unfortunately its refreshing when i comes to last tab and come back.kindly help me soon.

    • Pujan

      Do you find any solution?

      • Venktesh Sakthi

        no…not yet…have you??

      • Venktesh Sakthi

        i’m in a idea to change my tabs to navigation drawer

  • Gabriel Novaes

    how to change color icon image and text ?

  • Shubham Ojha

    Anyone here knows how i can send data from activity to view pager?

    • Abhinav Saxena

      Use FragmentStateAdapter POSITION_NONE, and fragments should have setters and getters, that you can use to update any data from outside and then call notify data set changed.

  • Muhamad Aditya

    step number 6 create a folder ….. what type folder? res or assets?

  • Venktesh Sakthi

    hai…im adding fetching data from sqlite in my third fragment.but its fetching when i comes to the second fragment.

    • Srinivas Guni

      Write your sql data fetching logic in setUserVisibleHint() method of third fragment simply by overriding . Then it should work only when your third tab is visible

  • Farhan Afandi

    hello, i’m try to use custom view tab but i have some problem, the text label on bottom of icon not on center. why this happen? sorry for bad english

  • Kuldeep Chaudhary

    can any one help me @ravi8x:disqus @disqus_e6bC2wGTJZ:disqus @venkteshsakthi:disqus @chandrasekharmajhi:disqus @@farhanafandi:disqus @disqus_AJDM4YrSjD:disqus @disqus_QqNMbwBsxp:disqus @disqus_zbKdBH3yaD:disqus @disqus_ALdmCgJcVI:disqus
    http://stackoverflow.com/questions/43466545/how-to-replace-fragment-in-tabs-view-pager?noredirect=1#comment73988638_43466545

  • Besart Mahmuti

    Hi great tutorial , i implemented Scrollable Tabs and is working great but when i enter scrollable tabs view in Fragment One , onCreate of fragment one and onCreate of fragment two are called , and when i go to Fragment Two , onCreate of fragment three is called and so on so when i enter Fragment nine onCreate of fragment ten is called and when i enter Fragment Ten nothing happens , any idea why is this happening ?, thank you in advance

  • Buntha Khin

    good example but you did not include main menu if compare with your video demo

  • Aditya Shah

    Great Tutorial Sir!
    Is there any way to make scrollable tabs dynamically from mysql database?

    So for example if there are 5 rows in a particular table of database, then on pressing a button the next activity should open with 5 tabs and along with their corresponding names.
    Is this possible

  • pammy

    awesome!

  • Marco Aurélio F. Venâncio

    How do I increase the size of the icon tabs? Thanks for the tutorial, very helpful! 😀

  • anand jha

    Bydefault my tab icons are coming above the text. But i want theze tab icons horizontally with the text. How can i do this.

  • sonali kale

    hello Sir,

    I want to kill background service.

    (i start service when login my app and when i logout i want to stop that background running service in my case when i stop that service by calling stopService() then also it runs)

    then how can i manage it please answer me .

    thank you .

  • Bruno Chichava

    Hi,

    How to use diferent drawables to diferent tab stages? For e.g when the page is selected and not selected.

    Thanks in advance.

  • Vikash Gunjan

    Hi All,
    I am looking for layout tab and scrolling bar over there. I found this in most of the tabs. but unable to make it like this. i have attached the screen shot for Airtel app and looking similar layout with bottom tab and scrolling bar above. Please help me with the code.
    My MainActivity.java code

    import android.os.Bundle;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;

    import me.majiajie.pagerbottomtabstrip.NavigationController;
    import me.majiajie.pagerbottomtabstrip.PageBottomTabLayout;
    import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;
    import me.majiajie.pagerbottomtabstriptest.custom.OnlyIconItemView;
    import me.majiajie.pagerbottomtabstriptest.other.MyViewPagerAdapter;

    public class MainActivity extends AppCompatActivity {

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

    PageBottomTabLayout tab = (PageBottomTabLayout) findViewById(R.id.tab);

    NavigationController navigationController = tab.custom()
    .addItem(newItem(R.drawable.ic_restore_gray_24dp,R.drawable.ic_restore_teal_24dp))
    .addItem(newItem(R.drawable.ic_favorite_gray_24dp,R.drawable.ic_favorite_teal_24dp))
    .addItem(newItem(R.drawable.ic_nearby_gray_24dp,R.drawable.ic_nearby_teal_24dp))
    .build();

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
    viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(),navigationController.getItemCount()));

    navigationController.setupWithViewPager(viewPager);
    }

    private BaseTabItem newItem(int drawable, int checkedDrawable){
    OnlyIconItemView onlyIconItemView = new OnlyIconItemView(this);
    onlyIconItemView.initialize(drawable,checkedDrawable);
    return onlyIconItemView;
    }
    }

  • Mingli Technologies

    Hi, how do i put a button on one of the tabs?

  • Sankar Chakravarty

    Great article, now how can I pass data between different tabs ? can anyone give me an example? Thanks in advance.

    • You need to read about Fragment communication.

      • Sankar Chakravarty

        Thanks for the reply…do u have any article about fragment communication ?

  • abdul rasheed

    Hi Ravi

    In This Tab example when we run the Simple tabs initially selected tab will be in ONE Fragment but the its running the TWO Fragment class code also . and When we select the second tab its running the THREE Fragment class code

    can u assist me how to come out from that.. because i want only First fragment class should run initally then when selecting the second tab it show run Second Fragment class i try to check using the logcat intially its running ONE and TWO class

  • Muhamad Aditya

    excuse me, how can i download other tab icon material resource?

  • fazeel zama

    Hello Ravi, Your code is very helpful for me. Thanks. But I am facing one problem while integrating it with my current project. I am having one navigation drawer and onClick of item on navigation drawer, the scroll tab should be open. But unfortunately it is not running and app gets crash..please help

  • Bassu Rai

    Hi Ravi
    thanks for sharing this excellent tutorial among with us
    how i can open a desire tab (like tab two) on activity start instead of open tab one
    again thanks in advance.

  • snehal

    my tabs are not getting full width even setting it as tab gravity fill

  • kavie

    When I try Custom Tabs,I’m getting like this (Screenshot is added here). TextView is not aligned properly,Can i get help to resolve this issue?

    https://uploads.disquscdn.com/images/3c033a9ba3ad44b53ea962e4a2f5775281612df31806482a4955908684924bcd.png

    • andrea
  • kavie

    Hi,
    When I try “Text & Icon” in Tab I’m getting Icon above textview instead of left,Screenshot is added here.But In downloaded code it is working fine,I’m not getting what i missed.Please help me to resolve this issue?

    https://uploads.disquscdn.com/images/8c4cb34b1d520d9b52e2514ef105283eba274054301cda3e69ebaa14003b0ea2.png

    • Artem Fomchenkov

      Try use only this versions of libraries (replace in Build.Gradle):

      compile ‘com.android.support:appcompat-v7:23.0.1’
      compile ‘com.android.support:design:23.0.1’

  • Geo K

    Good day!

    I wanted to go new version library.
    I changed gradle.build file (in Android Studio)!

    Instead:
    compile ‘com.android.support:appcompat-v7:23.3.1’
    compile ‘com.android.support:design:23.3.1’

    I wrote:
    compile ‘com.android.support:appcompat-v7:25.3.1’
    compile ‘com.android.support:design:25.3.1’

    At once I received ERRORS while testing into Google Developer Console (on the Google website).
    With library 23.3.1 – 14 devices work normally,
    with 25.3.1 – 11 devices work norm, 3 devices don’t work!

    Test Report with ERROR for Galaxy S7 Edge Android 6.0:

    java.lang.RuntimeException: Unable to start activity ComponentInfo{ru.englishtenses.key_FREE/ru.englishtenses.key_FREE.ScrollableTabsActivity}: android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class android.support.design.widget.AppBarLayout

    FATAL EXCEPTION: main
    Process: ru.englishtenses.key_FREE, PID: 30079
    java.lang.RuntimeException: Unable to start activity ComponentInfo{ru.englishtenses.key_FREE/ru.englishtenses.key_FREE.ScrollableTabsActivity}: android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class android.support.design.widget.AppBarLayout
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3253)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
    at android.app.ActivityThread.access$1100(ActivityThread.java:221)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7224)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
    Caused by: android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class android.support.design.widget.AppBarLayout
    at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
    at android.support.v7.app.k.b(Unknown Source)
    at android.support.v7.app.c.setContentView(Unknown Source)
    at ru.englishtenses.key_FREE.ScrollableTabsActivity.onCreate(Unknown Source)
    at android.app.Activity.performCreate(Activity.java:6876)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
    … 9 more
    Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class android.support.design.widget.AppBarLayout
    at android.view.LayoutInflater.createView(LayoutInflater.java:657)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
    … 17 more
    Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.newInstance(Native Method)
    at android.view.LayoutInflater.createView(LayoutInflater.java:631)
    … 22 more
    Caused by: java.lang.NullPointerException: Attempt to get length of null array
    at android.support.design.widget.AppBarLayout.onCreateDrawableState(Unknown Source)
    at android.view.View.getDrawableState(View.java:18350)
    at android.view.View.drawableStateChanged(View.java:18260)
    at android.view.ViewGroup.drawableStateChanged(ViewGroup.java:6672)
    at android.view.View.refreshDrawableState(View.java:18328)
    at android.view.ViewGroup.setAddStatesFromChildren(ViewGroup.java:6744)
    at android.view.ViewGroup.initFromAttributes(ViewGroup.java:643)
    at android.view.ViewGroup.(ViewGroup.java:591)
    at android.widget.LinearLayout.(LinearLayout.java:202)
    at android.widget.LinearLayout.(LinearLayout.java:198)
    at android.widget.LinearLayout.(LinearLayout.java:194)
    at android.support.design.widget.AppBarLayout.(Unknown Source)

  • varun v nair

    help pls..
    my imports already includes android.support.v4.app.Fragment but still it shows me this error “Found : com.sample.dude.tabbed.OneFragment https://uploads.disquscdn.com/images/357ca1ec89138e1352c7e7d45b40631d47a77825de05bc9498d39899e98865fb.png required android.support.v4.app.Fragment”.

    • varun v nair

      it is already there

    • Ashwin

      try importing just fragment instead of v4.app.Fragment

    • junetaja

      Change these import fragments class import with v4.app.Fragment
      OneFragment.class
      TwoFragment.class
      ThreeFragment.class

  • varun v nair

    Help …
    I want to change the title name according to each of the fragments..what should i do?

    I used “getActivity().setTitle(“Details”);” but its not working.

  • SHUBHAM CHAUHAN

    hey thankx for the tutorial, can you write a program for combining navigation drawer and tabs in single activity.

  • Chirag Joshi

    can we change width of tab indicator ???

  • asampayo

    Hello guys
    How can I display a listview using ArrayAdapter on tab?

    Thanks

  • minh nv

    how can I change the text content of pager ( change by java code, not by resource )

  • varun v nair

    hey sir, I need a help. I want to change that tab indicator(Currently it is an underline) to circle. How could i do that?

  • development techlab

    sir how can i add the drawer Layout with tabLayout

  • chetan

    Hi,
    thank’s for this tutorial,
    I want to change tab icons when select and deselect (when tab selected different tab icon need to come,else default means old tab icon need to display).

  • Vempati Satya Suryanarayana

    Nice tutorials

  • Anton Wycoco

    Hi,
    What if I want to put the layout on the bottom of the layout.
    Is it possible? Thank you.

  • Tiaguinho Alex

    Thank you so much. from Brazil

  • Mayank Jariwala

    @ravi8x:disqus What should i do to navigate to second tab on clicking button on first fragment(i.e Tab)?

  • Hannah Akinyi

    Thanks for this.

  • https://uploads.disquscdn.com/images/72a7ebfdeb09bbcd99e9c6928641d61bcc0beb85c8932fdfe97a7c97e69d7a9b.jpg

    I want achieve

    FragmentA have two layout FragmentA1 and FragmentA2

    FragmentA1 have recycler view
    FragmentA2 have tab layout, view pager

    When click item in recycler view
    Change tab layout like below image

    Please help me …
    Thanks

  • Richard Leandro

    how set icon size?

  • Rohmad Arifin

    Hi Ravi Tamada, this tutroal the best ever tutorial… i need your help with customize tabs textview, how to set width size textview ???

    Thanks!