Android TabLayout Example using ViewPager and Fragments

If you are using the latest android application then you have noticed that now days android is following a design pattern. This is material design and it came with Android Lollipop (5.0). Though we can still use this design pattern for the older versions (>4.0) by using the support libraries. One of the component of material design is TabLayout. So in this Android TablLayout Example we will see how we can implement it in our android application. You may have already seen Android TabLayout Example in the apps you use daily.  For example WhatsApp the home screen is an Android TabLayout Example from where we switch to calls, chats and contacts.

So lets see in this Android TablLayout Example how we can implement the same in our android project.

What is Android TabLayout?

Android TabLayout provides horizontal layout to display tabs. We can display more screens in a single screen using tabs. User can swipe the tabs quickly as you can see in the image below.

android tablayout example
Android Tablayout Example

Android TabLayout Video Tutorial

  • Check this updated video tutorial for Android TabLayout.

Creating our Android TabLayout Example

  • Open Android Studio and create a new project.
  • I have created AndroidTabLayout.

Adding Design Support to our Project

  • We have to add design support library to the dependencies. So right click on app and to go module settings.

module settings

  • Now go to dependencies tab and click on the + button and select library dependency.

library dependency

  • Select design and click on ok.

choose library dependency

Creating Layouts for the Tab Views

  • We have to create the layout resource files for our tabs. As in this project I will be displaying 3 tabs so I need to create 3 layout files.

project

  • You can see in the image I have tab1.xml, tab2.xml and tab3.xml. All these files are having the same code you can see below.

  • Just change the android:text=”Tab tab_number”,for every layout file to see the tabs are switching or not.
  • For these 3 layout resource files we also need to create 3 java classes that will contain these resource as fragment.

source

  • Create these 3 classes in your project (Tab1, Tab2, Tab3). The code would be the same for every class. Write the following code inside these 3 classes.

  • You just need to change the R.layout.tab1 for Tab1.java, R.layout.tab2 for Tab2.java and so on.

Creating a pager adapter

  • We need a pager adapter to swipe views. So create a new class named Pager.java. and write the following code.

Removing Actionbar

  • Now one thing we just forget. We have to remove the action bar and we will use the toolbar instead. So go to values -> styles.xml and change the app theme.

Creating TabLayout and ViewPager

  • Now we will create our TabLayout, so come inside activity_main.xml and write the following code.

  • Now come to MainActivity.java.

  • In the above code we have implemented the interface OnTabSelectedListener. As we implemented an interface to our class we have to override the methods of this interface. Override the following methods inside MainActivity.java.

  • Now come inside onCreate() and write the following code.

  • Now at last we only need to swipe the view when a new tab is selected. For this go to the overriden method onTabSelected() and write the following code.

  • So the final code for MainActivity.java would be.

  • Now run you application.
android tablayout example
Android Tablayout Example
  • Bingo its working absolutely fine. You can get the source code from below.

Android TabLayout Example Download Source 

So thats all for this Android TabLayout Example guys. Feel free to leave your comments if having any troubles and queries regarding this Android TabLayout Example Project. And stay tuned for more tutorials. Thank You 🙂

68 thoughts on “Android TabLayout Example using ViewPager and Fragments”

  1. Hi
    Dear Belal,
    Thank you for the amazing tutorials that you post.
    i was wondering if you can make new tutorial about “get current GPS location and store it in MySQL” as well retrieve it to the app so it can be used to know the direction with the help of google Maps

    Reply
  2. Thank you belal
    best posts ever!

    just a small problem when sliding through the tabs it seems like its staying in the same tab. I mean that the content of the tabs are switching correctly but the toolbar is not changing the selected tab.

    Reply
  3. Thank you belal
    Best Posts Ever!

    Just a small problem, when sliding(not selecting) through the tabs, the content of the page are switching correctly but the pointer on the toolbar are not changing.
    For example if I have 3 tabs each one having a text field “Tab1”, “Tab2″,”Tab3” respectively, then if I select first tab1 I’ll se “Tab1”, but if I slide to the next tab I can see Tab 2 but in the toolbar the Tab 1 remains selected. can you help please?

    Reply
  4. FIX: Tab title not changing when swiping

    Write the following code inside OnCreate fn.

    // When swiping between pages, select the
    // corresponding tab.
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
    //actionBar.setSelectedNavigationItem(postion);
    tabLayout.setScrollPosition(position,0,true);
    tabLayout.setSelected(true);

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }
    });

    It’s working, but still need some work for perfection.

    Reply
  5. Fix for Tab Title while Swiping

    Just add the below line in onCreate function in MainActivity

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    Below lines of code shows you where to add that line

    //Adding adapter to pager
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    //Adding onTabSelectedListener to swipe views
    tabLayout.setOnTabSelectedListener(this);

    Reply
  6. Hi! thanks for the awesome tutorials!

    If you swipe the page the tab indicator doesn’t change.

    Add this:

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    Peace!

    Reply
  7. Hi Belal Khan!

    I wonder if it is possible to disable finger swipe on the pages & only use ‘click on tab’ for the page navigation? I would hope that you provide me the assistance on customizing your source code.

    Thank you!

    Reply
  8. Hi Belal Khan!
    Plz tell me,
    How we can add an expandable list view items in those tabs??
    Please share the code.

    Reply
  9. Hello sir
    please you can help me.
    i want add in this tutorial
    Create Chat Application in Android using GCM
    so please you can make one more tutorial about adding any other tutorial.

    thank you

    Reply
  10. Thanks for the tutorial Belal. Just a suggestion:-
    Instead of adding any of the listener in main activity use the method tabLayout.setupWithViewPager(viewPager);
    and override the method getTitle in Pager class:
    public CharSequence getPageTitle(int position) {
    switch(position){
    case 0:
    return “Tab 1”;
    case 1:
    return “Tab 2”;
    case 2:
    return “Tab 3”;
    default:
    return null;
    }
    }

    remove these lines from MainActivity:
    tabLayout.addTab(tabLayout.newTab().setText(“Tab1”));
    tabLayout.addTab(tabLayout.newTab().setText(“Tab2”));
    tabLayout.addTab(tabLayout.newTab().setText(“Tab3”));

    No need to add any listeners in tablayout and viewPager, the both will be automatically linked.

    Reply
  11. Hi Belal: Nice simple example. With the suggested fix I was able to get the code working.
    However, when I went to recreate the files, I ran into an Android Studio error when I right clicked on the project and selected module. This is preventing me from adding library dependencies for the TabLayout and Widget functions.

    My minimum build level is 16. The error is:
    IllegalArgumentException: Multiple entries with same key: Google Inc.:Google APIs:16=Google
    APIs (API 16) and Google Inc.:Google APIs:16=Google APIs (API 16)

    Reply
  12. 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 custom tab layout :-
    ————————————————————

    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 ?

    Reply
  13. hi ~
    thank you for your tutorial.
    but if i slide between the tab (not click on the tab)
    the content is able to change to next tab
    but tablayout wont change still remain on the first tab

    Reply
  14. How to enable clicking the tab to switch between layout?

    Its already switch to another layout on swipe, but ia want to it change the layout on select the tab.

    Reply
  15. setOnTabSelectedListener is deprecated, instead now use: addOnTabSelectedListener

    tabLayout.addOnTabSelectedListener(this);

    Reply
  16. Adding a custom layout to be rendered when a specific tab is clicked or touched is a problem. When I do this the tab name disappears and seems to be replaced by the custom layout. How should I resolve this problem?
    Otherwise, useful example.

    Reply
  17. Hiii
    How can i remove swipe of tabs?
    actually i have to change tabtext-color and tab icon on tab select and swipe i have used selector method(state_selected) but it worked for tab select not on tab swipe. so how can i do that or i have to remove swipe.

    Reply
  18. hi ,
    i have applied ur code in my apps and it works fine..but i have recyclerview and on each item click it should open those item clicked data into different tabs(now i am inserting data through static method and each item has atleast 10 different types of data)..how can i achieve it in my apps???()

    Reply
  19. In the activity_main the Tablayout should be placed below the ViewPager to enable clicking the tabs also possible if you do not want to swipe

    Reply
  20. i want to indicater in second tab or in center of tab in defult how can i do that?when i open a project tab must be in a center or tab2 like in this project in a tab 1

    Reply
  21. Suppose i created a button in all three tabs and i wanted to open a new activity when i click on that button how can i do it any example code (of tab.java) will hep me a lot.

    Reply
  22. hiii !!
    your code really helped me a lot bro !!
    i was trying for more than a week but was not able.
    but just having a single problem, in my case tab names are not showing.
    rest all is working great swiping etc
    can you help me out.

    Reply
  23. Hi Belal.I am the big fan of you and your code is very helped me.But now we can’t download full code without login in facebook. and there is many type of fishing to hack our facebook password. Hope you will keep our login details safe and secured. Thank you for your help

    Reply
  24. Anyone know how to parsing data from php (mysql) on each fragment and show it on recyclerview and cardview? For example tab1 for database1, tab2 for database2 and tab3 for database3. Thanks.

    Reply
  25. this is my error:
    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.
    please help

    Reply
  26. How to disable the swipe functionality of viewpager. I want to change the fragments only when tab is clicked.

    Reply
  27. hi bro, thanks for the tutorial. i have one small request.
    when i implement intent in one of those fragments, action bar is not visible. so can you please shed some light on this?

    Reply
  28. Thank you very much.

    Are there any examples that have two menus? Horizontal menu and one side menu (Navigation Drawer and TabLayout) using ViewPager and Fragments.

    I haven’t seen any tutorial that explains how to do it, I’m not very put in programming, anyway you can’t do it, but having these two options is interesting.

    Does anyone know a tutorial that explains how to do it?

    .

    Reply

Leave a Comment