Material Design Tabs with Android Design Support Library

This is my third post where I continue to bring you more from the Design Support Library. Let’s look at adding a Material Design Tab strip for our apps with on scroll animations.

Tabs make it easy to explore and switch between different views. Provides a way for displaying grouped content. – source

Material Design Tabs made easy

You can see Material Design tabs popularly on the Play Store app, and more recently on WhatsApp as well (after their Material Design update).

material design tabs in play store app

Material Design Tabs in Play Store

Tabs in WhatsApp

To implement Tabs earlier, we had to rely on external libraries. Also, let’s not forget the hide on scroll animations which we had to make ourselves!

When you’re done reading this post, you’ll be able to create amazing Material Design tabs for your apps. Like the ones above.

So let’s get to it!

Also read:


Layout

Have you closely observed how Tabs actually behave?

When you click a Tab, it becomes active and slides in a new screen. Rather a new sub-screen called Fragment. We either tap a Tab, or swipe left or right to access adjacent Tabs.

Tabs are typically found anchored to the bottom of the Toolbar.

In essence, the entirety of those Tab screens are Fragments, which will be handled by a ViewPager. Think of it like a gallery slideshow.

But before we dive into all of that, let’s setup our main layout.

Here’s a skeleton of the layout.

<android.support.design.widget.CoordinatorLayout >

    <android.support.design.widget.AppBarLayout >

        <android.support.v7.widget.Toolbar />

        <!-- The Tab rests directly below the Toolbar, attached below it -->
        <android.support.design.widget.TabLayout />

    </android.support.design.widget.AppBarLayout>

    <!-- Helps handing the Fragments to load for each Tab -->
    <android.support.v4.view.ViewPager />

</android.support.design.widget.CoordinatorLayout>

For creating Tabs, we use the TabLayout widget class. This is a new widget, part of the Design Support Library.

Additionally, you might notice other new widgets as well. If you’re not familiar with them, I strongly suggest you go through this post first.

That’s the skeleton of our Activity layout. Let’s start defining it now. Open your Activity’s layout.xml

<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: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:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

The scroll flags for the Toolbar specify how it must behave upon scroll (i.e. its animation).

scroll|enterAlways says make my Toolbar react to scroll events. Hide it when scrolling down, and reveal it when scrolling back up.

This behavior will be indicated by our ViewPager which will be hold our Fragments. The Fragments hold our scrollable view. So when we scroll down a list, the Toolbar knows when to react.

Tabs attached below Toolbar

TabLayout and Toolbar in XML preview

Setting up TabLayout

That’s our main layout. Now open up YourActivity.java.

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

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

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

First, start off by setting up your Toolbar. Then define the ViewPager. We’ll attach an Adapter to in the setupViewPager() method. Finally define the TabLayout, and attach the ViewPager to it.

Remember that we must attach an adapter to the ViewPager first. Then attach the ViewPager to TabLayout.

setupViewPager() method

Here I will simply initialize a ViewPagerAdapter (our custom adapter class which I will explain in a moment) and add 3 fragments to it.

For simplicity’s sake, I will be attached the same Fragment thrice which different backgrounds. However in a real app scenario, you would be attaching different once.

Let’s assume you have 3 tabs. Games, Movies, Books. Then you should be loading their respective fragments here in ORDER of the tabs.

Android Material UI Template 8 in 1 CodeCanyon
private void setupViewPager(ViewPager viewPager) {
      ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
      adapter.addFrag(new DummyFragment(getResources().getColor(R.color.accent_material_light)), "CAT");
      adapter.addFrag(new DummyFragment(getResources().getColor(R.color.ripple_material_light)), "DOG");
      adapter.addFrag(new DummyFragment(getResources().getColor(R.color.button_material_dark)), "MOUSE");
      viewPager.setAdapter(adapter);
  }

So let’s define our Tabs and give each one a name. Cat, Dog and Mouse (for the lack of better names) will be my 3 Tabs.

Defining our Adapter

Remember that ViewPagerAdapter I told you about? Let’s create a class for it now, extend FragmentPagerAdapter and implement the required methods.

We need to store, first our Fragments itself, and then the Tab titles. We’ll do this with a List.

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

Our entire Adapter class will look like this:

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);
        }
    }

Note that addFrag() is my own custom method. I’m using it to add Fragments and its titles to the ViewPager adapter.

tabs-defined

Tabs with ViewPager Adapter

Tab Fragment

Now that we’ve done all this, you might be wondering what is ‘DummyFragment‘ and why its showing an error?

DummyFragment is to be your Fragment (obvious from the name), which holds the layout content. This is what we see when we swipe to each Tab. Ideally, you should be loading a different Fragment for each tab.

The layout could be anything. But I don’t want to complicate things.

Just be sure for testing, to make a list long enough so that its scrollable. This will allow the Quick Return scroll animation to work.

I encourage you to create your own layouts for the Tab Fragment. You could refer mine, but if you’re like “Hey, I can do this!“, then good job! Scroll down to the next section.

public static class DummyFragment extends Fragment {
       int color;
       SimpleRecyclerAdapter adapter;

       public DummyFragment() {
       }

       @SuppressLint("ValidFragment")
       public DummyFragment(int color) {
           this.color = color;
       }

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

           final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
           frameLayout.setBackgroundColor(color);

           RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);

           LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
           recyclerView.setLayoutManager(linearLayoutManager);
           recyclerView.setHasFixedSize(true);

           List<String> list = new ArrayList<String>();
           for (int i = 0; i < VersionModel.data.length; i++) {
               list.add(VersionModel.data[i]);
           }

           adapter = new SimpleRecyclerAdapter(list);
           recyclerView.setAdapter(adapter);

           return view;
       }
   }
tabs with list

Tabs with Fragments attached

Tab Listener

We can interact with the TabLayout and dictate what must happen when selecting a Tab, unselecting, reselecting and so forth.

While we’re staying on topic, let me show you how we can add such a listener to it.

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                viewPager.setCurrentItem(tab.getPosition());

                switch (tab.getPosition()) {
                    case 0:
                        showToast("One");
                        break;
                    case 1:
                        showToast("Two");

                        break;
                    case 2:
                        showToast("Three");

                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

Note viewPager.setCurrentItem(tab.getPosition()) handles changing the Fragment based on Tab click.

Yes, all it takes is to use setOnTabSelectedListener with TabLayout.OnTabSelectedListener().

Just for demonstration, I’ll show a simple Toast when you tap a Tab item. This works not only when tapping, but also when swiping left or right! In essence, a Toast pops each time the Fragment loads into view.

v23.0.0 Tab Listener Fix:

With the release of Android Marshmallow, libraries got updated to 23.0.0 including the Design Support Library. This update somehow broke the tab listener in a viewpager + tab combination. So if click listener for the tabs stops working for you, here is a suggested workaround for it, suggested by Chris Banes himself.


Material Design Tabs in Action

Let’s take a breath and break down what we’ve accomplished so far:

  1. Created our main TabLayout
  2. Initialized a ViewPager and attached an Adapter (ViewPagerAdapter) to it
  3. Attached the ViewPager to our Tabs
  4. Created the Fragment content to supply our ViewPager with

Finally with all that code behind us, lets run our app and see how it looks like.

 

That’s it! We’ve got some great looking Material Design Tabs (without a third party library). Created the needed adapter and even got those snazzy on scroll animations for our Toolbar.

Note the Tab underline highlight takes colorAccent by default. Also, did you just notice we got those animations to work just by defining it in XML? No Java. Cheers!

Thats what Android Design Support library allows us to do. Making the easy stuff easier.

Source Code:
Find this code sample on GitHub.

How are you using TabLayout in your apps? Have anything else to add? Let me know in the comments.

P.S. You can even download this article as a FREE eBook. Just use the form below to grab your free copy!

Enjoyed this article? Please spread the word.

Material Design Tabs FREE eBook!

Download this article in PDF format.
DOWNLOAD FREE EBOOK
Written for you, by Suleiman from Grafix Artist.

Suleiman

An App developer with an eye for design. Loves to create apps with good UI/ UX that people appreciate. In his spare time, he likes to draw and paint.

You may also like...

  • In your codes, when tabs are clicked, ViewPager won’t change pages even you have set OnTabSelectedListener . You should set ViewPagerOnTabSelectedListener on your TabLayout. BTW, do you think it’s a bug inside TabLayout?

    • Hi Peter,
      Thanks for pointing it out. While the listener itself needn’t be changed, just add this line in the onTabSelected method, before the switch case:
      viewPager.setCurrentItem(tab.getPosition());

      I’ve updated the post and GitHub repository. Thanks for following the post with a watchful eye.

  • Andrii

    Hello!! I’ve just copy your repository and try to launch and I noticed that neither “Toolbar Animation wih image” nor “Material Style Tabs” works. I’ve tested on Genymotion 5.1 and Android 4.4. This is dependencies I’m using
    compile ‘com.android.support:appcompat-v7:22.2.0’
    compile (‘com.android.support:design:22.2.0’){

    }
    compile ‘com.android.support:appcompat-v7:22.2.0’
    compile ‘com.android.support:palette-v7:22.2.0’
    compile(‘com.android.support:recyclerview-v7:22.0.0’) {
    }
    compile ‘com.android.support:cardview-v7:22.0.0’

  • Andrii

    Oh, I’m sorry for previous post – i’ve tried just copy and paste main classes needed for tabs – and it didn’t work. However. in your project everything works fine, but I can’t understand where I could make mistake, because I’ve copied all java, resources and AndroidManifest files to brand new project

  • Andrii

    Ok. I’ve spent 1 day to realize that Google silently updated recyclerview!!! So I’d used 22.0.0 and even imagine that it can cause problem with material hiding. When I changed to 22.2.0 everything seems to work.
    PS: Great article, but it would be great if you can point at such kind of misunderstanding

    • Sorry to hear you wasted a day finding that out. But glad you finally got it to work! Thanks for the pointer. Will make it clear for future readers.

      PS: Make sure you update ALL respective libraries together 😉

  • Anuj Mody

    how to do with icons in tabs without text???

    • Use this:
      tabLayout.getTabAt(index).setIcon(icon).setText(“”);

      • Anuj Mody

        Thanks sir, and what if i want both txt and image then?

        • Its there in the same code snippet. Use setText(“YourTabName”);

          • Anuj Mody

            Thanks a lot sir ????

          • Anuj Mody

            Thanks a lot sir it working fine now.Now i have one more doubt.I have differnt images when the user is on particular page of view pager.So how will i change the icon on page scrolled?

          • It is not recommended to keep changing the tab icon/text during use, as it would only confuse the user.

  • Mateusz Pryczkowski

    If in your fragment, you are not using RecyclerView, but you have simple ScollView – in this case hiding toolbar won’t work. In this case please use – android.support.v4.widget.NestedScrollView

    • Correct. Thanks Mateusz for sharing a useful pointer!

      • Sayooj valsan

        Hi, I was following the example and Yes I dont have a RecyclerView. I just have a simple Listview in the fragment. How do I make the hiding work when I scroll ?

        • Hi Sayooj,
          Please migrate to RecyclerView

          • Akshay Labhshetwar

            yo can use NestedListView

            import android.content.Context;
            import android.util.AttributeSet;
            import android.view.View;
            import android.view.ViewGroup;
            import android.widget.ListAdapter;
            import android.widget.ListView;

            public class NestedListView extends ListView {

            private static final int MAXIMUM_LIST_ITEMS_VIEWABLE = 99;

            public NestedListView(Context context, AttributeSet attrs) {
            super(context, attrs);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);

            int newHeight = 0;
            final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            if (heightMode != MeasureSpec.EXACTLY) {
            ListAdapter listAdapter = getAdapter();
            if (listAdapter != null && !listAdapter.isEmpty()) {
            int listPosition = 0;
            for (listPosition = 0; listPosition < listAdapter.getCount()
            && listPosition heightSize)) {
            if (newHeight > heightSize) {
            newHeight = heightSize;
            }
            }
            } else {
            newHeight = getMeasuredHeight();
            }
            setMeasuredDimension(getMeasuredWidth(), newHeight);
            }

            }

          • Hi Akshay,

            While that is a great and viable solution, I urge you to consider the advantages RecyclerView offers. Maybe giving this a read can help? http://stackoverflow.com/questions/28525112/android-recyclerview-vs-listview-with-viewholder

    • Srujan Barai

      Thank you @mateuszpryczkowski:disqus
      You saved my life.

  • Rafael de Araújo

    The best tutorial of Tabs using material design lib!

    • Thank you for the kind words Rafael 🙂

  • adao7000

    Let’s say that I have a navigation drawer that selects either Frag1 or Frag2. How can I adapt this code so that Frag1 has the sliding tabs (like in this post), but Frag2 doesn’t?
    I have a StackOverflow question about this: http://stackoverflow.com/questions/31091644/implementing-sliding-tabs-in-a-fragment

    Edit: Never mind, I figured it out! My xml layout wasn’t putting the ViewPager on that screen, so I couldn’t swipe!

    • Great. Glad to know you figured it out!

  • Kevin Chris

    For me whenever I swipe slowly from one tab to another, in between if I stop swiping the tab indicator get struck in between the Tabs. Is there any solutions to fix this?

    • Hi Kevin,
      That behavior which you’re describing is weird. If you take a look at my Youtube video, I swipe past the Tabs slowly and it doesn’t get stuck in between. Could you try doing a clean rebuild? Make sure your updated all build tools and libraries to their respective latest versions as well.

      • Kevin Chris

        Its happening like attached Image. These are the version I’m using. All are latest
        compile ‘com.android.support:appcompat-v7:22.2.0’
        compile ‘com.android.support:support-v4:22.2.0’
        compile ‘com.android.support:design:22.2.0’
        compile ‘com.android.support:cardview-v7:21.0.+’
        compile ‘com.android.support:recyclerview-v7:21.0.+’

      • Kevin Chris

        Its happening in my scenario! Couldn’t resolve still

        • Have you tried what I suggested?

        • Susie

          Me too,But I resolved this problem,I setId for viewPager like this:viewPager.setId(View.generateViewId()); you can try.My English is very poor.Hope useful to you.

          • Thank you for that Susie. I’ve never faced this issue. Not able to reproduce it either, so I’m afraid I can’t be of help here.
            However, I’m sure this can help those who have this issue 🙂

      • The last update of Support Lib (23.1.0) doesn’t fix this issue

    • Roberto Mirra

      Me too! Have you resolve?

    • The issue is seems to because of not created Fragments (empty) in ViewPager. You should clear ViewPager items before add new fragments. See this solution: http://stackoverflow.com/a/11442623/1621111

  • Poonam Kukreti

    Hi,I want to call tabs in navigation drawer how can i do that ?

    • You can use an interface that calls the tabs upon drawer item click

  • Raveesh

    ur tuts very easy to understand for a common for person.. keep posting,keep sharing..

    • Thank you for that Raveesh.
      Happy you like them. Do share so others find this content too.

      Cheers

  • rethinavel

    it would be really nice if you share your dummy_fragment.xml BTW, Have you ever tested the webview in fragment works as well? The toolbar is not hiding if the fragment element is webview! could you please help me?

    • Your Fragment can contain any layout. Doesn’t matter what it is. I haven’t tested WebView personally, but the content doesn’t really matter. Do cross check your layout arrangement against mine. There is a GitHub link at the end.

      Also update your Design Support Library to 22.2.1

      • erum hannan

        @suleiman19:disqus can u pls help me i have Linearlayout + tabs +Viewpager now i want to whle layout inside scrollview once i m doing i m unable to create swiping between tabs

        • Could you please elaborate? Swiping between tabs work (as you can see in my post). I’d say you cross-check against my project (GitHub) once.
          Otherwise do post on StackOverflow so that I can take a look.

    • Depp

      As Mateusz Pryczkowski pointed out above, you might wanna wrap the webview in a NestedScrollView, it works for me~

  • Aibek Mamatov

    Hello, Suleiman19!
    I’ve a problem. The toolbar does not hide when i scroll recyclerview. I make all that how you made here. Can you halp me? If you whant i can send github url of my project.

    • Make sure you cross check your layout against mine. Especially scroll flags for Toolbar and layout_behaviour for ViewPager.
      Also update your Design Support Library to 22.2.1

      • Aibek Mamatov

        thank You very much! a solve my problem.))

  • igoticecream

    Hello, I’m following your tutorial and my fragments are PreferenceFragments… when i inflate them my toolbar wont hide while scrolling.

    I’m using LinearLayout and fragment to show my preferences.

    Thanks.

    • The Preference Screen was never intended to have any such behavior such as the Quick Return. If you really want it bad, you can create a custom settings screen extending a normal Activity. Otherwise you should just focus on the Settings page behavior, rather than the animations.

  • Derrick Ozil Mugenyi

    Hey Suleiman19 can i have gridview in the fragment….and if i dont use recyclerView will the toolbar hide on scroll

    • I honestly haven’t tried a GridView Derrick, and wouldn’t want to give a false answer. As to my knowledge, any scrollable view would work.

      You could do a grid view using RecyclerView too. Just have to change the layout manager.

      • Derrick Ozil Mugenyi

        hey Suleiman thanks for the reply, i have managed to get the gridView in one of the tabs but i have tried so many ways to get the toolbar to hide on scroll but i have failed. PS: I havent used the recyclerView because it looks a bit complicated and long. The scrollFlags in the activity_main under Toolbar hasnt done any magic for me. But when i just design the Tabs and just include cardviews in the activity-main i am able to have the Toolbar to hide on scroll…. Any help will be great. Thanks

        • Maybe the GridView has some hiccups working with the Design Support Library. Like I said earlier, you can do a GridView with the RecyclerView as well. Its not at all complicated. I recently made a post you could follow specifically for this: http://blog.grafixartist.com/pinterest-masonry-layout-staggered-grid/

          Do note the only thing you need to change here is the LayoutManager from StaggeredGridLayoutManager to GridLayoutManager

  • JR

    Nice tutorial. Thank you so much. Saved me a lot of time with a very skilled approach.

  • Witalo Benicio

    Hey Suleiman19… is there a way to prevent Fragments to be recreated when changing pages?
    If i go to third page and went back to first, i can see my fragment loading views again.

    • use the onResume() and savedInstanceState()

  • marios zoutis

    Thank you very much for this great tutorial! Really helped me a lot! I have a question though. ViewPager seems to exceeds the height of the screen and goes beyond navigation buttons at the bottom. Is there a way I can make ViewPager view to stop at the bottom of the screen?

    • I need to see your layout before I can suggest a change. Make sure windowTranslucentNavigation in your styles.xml is set to false.

      • marios zoutis

        I have tried to set windowTranslucentNavigation to false, but this is supported from api 19 and above, my min sdk is 16.

        However my layout is:

        Edit: I use a list view in one of my fragments and a scrollview in another fragment. Autohide is not working. Maybe this is the case??

  • igoticecream

    Hello. With the new support library 23.0.0, that tab listener stops working, weird. Any ideas?

    • BrandonWhite116

      I have noticed this too. Specifically after swiping the view pager then tapping the tabs. I haven’t found a workaround yet.

      • igoticecream

        Well it is a bug introduced with the new version of the support library. Check this workaround https://code.google.com/p/android/issues/detail?id=183123

        • Thanks for the pointer. Shall update the post so future readers can find this link.

      • To check this issue out, I updated all my libs to 23.0.0. But I don’t face any issue. Seems to work fine for me.

        • BrandonWhite116

          It started breaking for me when I swiped from position 0 to 1 then did a tab tap on position 0. The fix that igoticecream posted worked for me.

  • Yiyo Castillo

    Hey, this a really great post about tabs. I’m doing an app and I try to follow this guide, however I found with a difficult situation about tablayout so I want ask you for help.

    I want do an app with a NavigationView that replaces a framelayout (main content) with a fragment when an option is selected but I need that only some fragments have tabs (tablayout) and others no. Please take a look at Google Play Music to give you an idea.

    I could not find a good way to do that, can you tell me what would you do? Thanks

    • Hey there,
      Happy to know that you liked the post.
      About what you’re trying to achieve, I believe the simplest solution would be to use a new Activity for that.

      Make a BaseActivity that includes your Drawer. So any Activity you extend with BaseActivity will have the drawer.

  • erum hannan

    i m trying LinearLayout(have some buttons and imageview) + tabs + viewpager its working fine in case of fragments viewpager is swiping and tabs are also working fine but i want to put the above layout inside scrollview so that i can scroll the whole screen instead of only viewpager fragment bcoz my viewpager contains listview so listview has very limited vertical space in S3 devices to scroll the data thats why i want scrolling screen but once i m trying to use scrollview then my viewpager fragments are not displayed @suleiman19:disqus how to resolved ?

    • Try using a NestedScrollView instead.

  • Kevin Hackett

    Thanks for the great tutorial. The one question I have is – how do you set it, when you have a 3 tab layout, that the middle tab is the one that is open/selected every time the app starts or goes back to the main view from another activity?

  • Julian Coronado

    Just found this post. Really helpful, but how I implement this into an app with a Sliding Navigation Drawer (that uses fragments?)

  • Juan Manuel Baez

    Hi, thank you for sharing this, its awesome, i hope that you could help me with an error that im having, im trying to migrate a project to the appcompat library, to use material design. But when i change a LinearLayout for a CoordinatorLayout in my xml, my log throws an error that says: “android.view.InflateException: Binary XML file line #1: Error inflating class android.support.design.widget.CoordinatorLayout”. If you got any idea, i will appreciate your help, thanks in advance.

    • Hi Juan, glad you like the post 🙂
      About your error, please post your layout. Atleast the CoordinatorLayout part, so I can try to see what’s wrong.

      • Juan Manuel Baez

        Hi Suleiman, i didn’t seen this, i have solved that problem, but now im trying to make your whole project work, the all in one that you share. I almost got it, but there is a lib that i can’t add, the CircularReveal one. It throws me Failed to resolve: com.github.ozodrukh:CircularReveal:1.1.1. I can’t find the .jar file to add it manually, any suggestion?

        Thanks in advance.

        • Hey Juan,
          Check your build.gradle files
          compile ‘com.github.ozodrukh:CircularReveal:1.1.0’

          Also this repository:

          repositories {
          maven {
          url “https://jitpack.io”
          }
          }

  • Gitahi

    Thank you for putting together this tutorial. I’ve followed it and almost everything works perfectly, except for one thing. The tab titles get wrapped if they are too long to fit in the available screen space, see the screenshot attached. Instead, I would like for such titles to stay on one line but slide into the edge, much like how the Google Play Store home page behaves. I’m guessing this should only take a slight tweak and I’ve tried to play around with settings on the TabLayout to no avail. Any suggestions will be appreciated.

    • My bet is that the screen is too narrow to accommodate Tabs. How does it look in landscape mode?
      Try using tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

      • Gitahi

        Just the thing I needed! Thanks a bunch.

        • Glad you found it useful Gitahi. Do consider sharing so others can know about it too.

  • Hi, I’m using android support library. Thank you for your blog post. Do you know how to change the ripple color of the tablayout?

    • Glad you liked it Myat. Consider sharing so others can find it too.

      To change the ripple color, create a new ripple drawable with your desired color under res/drawable-v21 folder and add an attribute to TabLayout like this:
      android:background=”@drawable/yourrippledrawable”

  • Dhrumit Shah

    Hi thanks for the great sample. I have problem AppBarLayout scrolls up even if no data in CAT,DOG or MOUSE tab. Please get back on this as soon as possible.Thank you.

    • You’re welcome Dhrumit.
      I haven’t experienced any of these issues. Have you updated all libraries to their latest versions?

  • Dhrumit Shah
    • Use match_parent for both layout_width and height in your RecyclerView. Tell me if that resolves it for you.

      • Dhrumit Shah

        I have already used match_parent for both width and height . Same thing is happening in your sample also.

        • The best solution for this would be to not enable the Quick Return at all. This is because from the looks of the screenshot, that Activity doesn’t look very content heavy. You don’t need a Quick Return for that. Your content already has enough room 🙂

  • Евгений Мацюк

    Hello everbody!
    Maybe it’s trivial question but i can’t find answer.
    When i click to tab fragment switched too fast. How to reduce speed fragment switching?

    • Try using a handler. However this is not an ideal behaviour. Do test on different devices just to be sure.

  • Gundeep Singh

    I followed your tutorial and made the app bar…but I’m stuck at a place…please answer this so question http://stackoverflow.com/questions/33436398/how-to-autohide-v7-appbar-when-scrollin-hides-it-partially-android

    • Hi Gundeep,

      The latest Design Support library added a new scroll flag ‘snap. Add it to your Toolbar’s layout_scrollFlags.

      The same answer is already suggested by a user on StackOverflow. 🙂

  • Gurappa Ch

    Hi Suleiman,

    It works fine for me too as it is supposed to. But one issue is that the tabs does not move and become visible automatically. Say I have 5 tabs. 3 are visible and 4th one is half visible. When I select 4th tab, it does not come to visible. Same when i swipe. When I swipe to 5th page (of viewPager), 5th tab is still off the screen and not visible.
    How to make the tab layout keep scrolling automatically when swiping the view pager to right or left so that tab layout shows the currently selected tab in middle always. And rest of the tabe on it’s left or right ?
    Thanks again for the help with the article.

    • Gurappa Ch

      I tried with GRAVITY_FILL but of no use.

      • Gurappa Ch

        I could find solution for this. I had to do tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE) or app:tabMode=”scrollable” in XML.

        • Hi Gurappa,

          That is precisely the solution. Brilliant!
          Good to see you kept trying and found the solution on your own. Sign of a good developer 😉
          Cheers.

          • Gurappa Ch

            Thanks!
            Thanks for the article again. 🙂
            Of course, I will share it with friends 🙂

  • This doesn’t works into Fragment instead of Activity

    • If you want it to work with Fragments, a simple idea is to add the TabLayout to your parent Activity. Then just do .setVisible(View.VISIBLE) for the Fragments that need Tabs, and View.GONE for those which don’t.

  • Joel Akoupo

    hi Suleiman19 ,

    when i compile your code,my IDE show :

    Error:(19, 5) error: cannot find symbol class SimpleRecyclerAdapter
    Error:(28, 46) error: cannot find symbol variable dummy_fragment
    Error:(29, 77) error: cannot find symbol variable dummyfrag_bg
    Error:(31, 9) error: cannot find symbol class RecyclerView
    Error:(31, 38) error: cannot find symbol class RecyclerView
    Error:(31, 74) error: cannot find symbol variable dummyfrag_scrollableview.

    i use as library :

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

    }
    compile ‘com.android.support:appcompat-v7:22.2.0’
    compile ‘com.android.support:palette-v7:22.2.0’
    compile(‘com.android.support:recyclerview-v7:22.0.0’) {
    }
    compile ‘com.android.support:cardview-v7:22.0.0’

    thank yu

    • Hi Joel,
      The current support libraries are on version 23.1.1 and build tools is on 23.0.2.
      Please update and see if that solves the issue.

  • Thalles Santos

    How do I change the title of the tab by an icon, like the Instagram tabs?

  • Jai

    Does anyone know how Google App Runtime change of AppBarLayout color ?

    http://stackoverflow.com/questions/36393840/runtime-change-of-appbarlayout-color

  • binoy balu

    Hey There. I’m not able to click cards inside of the viewpager which is implemented by recyclerview. I think something is overlapping with the same. Can you help me implement a Coordinatorlayout>Appbar>Toolbar>Tablayout>Viewpager and inside viewpager i have to click

  • Acea Alex

    Hey, I made a TabLayout like this one with 2 tabs containing fragments with recyclerviews. Thing is my recyclerview items contain checkboxes. In each fragment I have a method that knows which items are selected.
    I want to have a button in the Parent Activity and call the fragment methods from it. Thing is when I do that it always returns null. Can you help me with that? Thanks a lot!

    • Hi Alex,
      You can fetch the Fragment in your Activity like this (assuming you have a ViewPager setup):
      YourFragment fragment = (YourFragment) pagerAdapter.getRegisteredFragment(position);
      fragment.yourMethod();

      Of course, the success of the call depends on whether your Fragment is active, so you’ll have to check for that before making a call.
      Hope that answered your question.

  • Antonis Freris

    Hello, Thanks for the great tutorial. So i build this App that gets “text” from my uni and i parse it.
    Each semester has different Lesson names,grades ,etc, can i achieve it with this tutorial?
    I get stuck at DummyFragment that displays in every tab the same Lessons
    Any ideas on how to get fragment/adapter to show different lessons for each semester?
    Thanks in advance!

    • Use the fragment’s setArguments() method to pass different “text” to each Fragment. Then based on that you can load your lessons accordingly.
      Hope that answered your question Antonis, and I’m glad the tutorial helped you.

      • Antonis Freris

        Thanks a lot for your answer mate 🙂

  • Jalal Atsakzai

    Hi,

    Though I used a different approached on the tabs and fragments, I was wondering how i could set the list items more rounder corners like yours.

    • Hi Jalal,
      The list items are simply using CardView 🙂
      Use the “card_view:cardCornerRadius” attribute in its XML and you’re good to go. Alternatively, you can check the code sample (end of post) for reference.

  • Jack

    LoopBar – brand-new library of Tab Bar with Infinite Scrolling for Android. In my opinion, it looks very cool!
    https://github.com/Cleveroad/LoopBar

    • Hi Jack,
      That’s one amazing library! Really unique and brilliantly designed. I’m sure this will break the monotony of the ‘usual’ Tab Bars.
      Thanks for sharing my friend .

  • Clelia

    This was super helpful, as always. Thank you very much.

  • geethadevi

    Awesome Approach about tabs with android support library..I found what i needed..Thanks

Enjoyed this article? Please spread the word.

Material Design Tabs FREE eBook!

Download this article in PDF format.
DOWNLOAD FREE EBOOK
Written for you, by Suleiman from Grafix Artist.

12 Tab themes, 100+ Components & more!
Save time and develop faster with this app.
  • Ready-to-use XML & Drawables
  • Pre-coded, customizable UI
  • Trusted by 2300+ devs
GET THE APP
Don't miss this App Template (12 tab themes & more) !