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.
– Material Design, Tab Component
This article has been updated for AndroidX!
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).
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:
- Parallax Scrolling Tabs with Design Support Library
- Flexible space with header image pattern
- Quick Material Design Navigation Drawer with Design Support
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.
<androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.appbar.AppBarLayout>
<androidx.appcompat.widget.Toolbar />
<!-- The Tab rests directly below the Toolbar, attached below it -->
<com.google.android.material.tabs.TabLayout />
</com.google.android.material.appbar.AppBarLayout>
<!-- Helps handing the Fragments to load for each Tab -->
<android.support.v4.view.ViewPager />
</androidx.coordinatorlayout.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
<androidx.coordinatorlayout.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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<androidx.appcompat.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" />
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.appbar.AppBarLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.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.
Setting up TabLayout
That’s our main layout. Now open up YourActivity.java.
final Toolbar toolbar = findViewById(R.id.tabanim_toolbar);
setSupportActionBar(toolbar);
final ViewPager viewPager = findViewById(R.id.tabanim_viewpager);
setupViewPager(viewPager);
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.
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.blue_grey)), "CAT");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.amber)), "DOG");
adapter.addFrag(new DummyFragment(
ContextCompat.getColor(this, R.color.cyan)), "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.
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 = view.findViewById(R.id.dummyfrag_bg);
frameLayout.setBackgroundColor(color);
RecyclerView recyclerView = view.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
List<String> list = Arrays.asList(VersionModel.data);
adapter = new SimpleRecyclerAdapter(list);
recyclerView.setAdapter(adapter);
return view;
}
}
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:
- Created our main
TabLayout
- Initialized a
ViewPager
and attached an Adapter (ViewPagerAdapter) to it
- Attached the
ViewPager
to our Tabs - Created the
Fragment
content to supply ourViewPager
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.
How are you using TabLayout in your apps? Have anything else to add? Let me know in the comments.
Product Designer who occasionally writes code.
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.
http://stackoverflow.com/questions/32398500/toolbar-in-appbarlayout-is-scrollable-although-recyclerview-has-not-enough-conte
Any Solutions?
Use match_parent for both layout_width and height in your RecyclerView. Tell me if that resolves it for you.
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 🙂
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?
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”
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);
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, 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.
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”
}
}
Just found this post. Really helpful, but how I implement this into an app with a Sliding Navigation Drawer (that uses fragments?)
If you’ve taken a look at my Navigation Drawer post: http://blog.grafixartist.com/easy-navigation-drawer-with-design-support-library/
You will note that a FrameLayout with id nav_contentframe exists. This is used to inflate a Fragment view. You can use this to inflate a Fragment which holds your Toolbar+Tabs.
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?
Hi Kevin,
This should help you out: http://stackoverflow.com/questions/30796710/tablayout-tab-selection
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.
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.