How To Make Material Design Sliding Tabs

04:18 234 Comments

In this tutorial we are going to implement sliding tabs in material design style by using the SlidingTabLayout from Google iosched app, The SlidingTabLayout is also provided on the Google developer page as well but it isn't updated with some methods such as setDistributeEvenly() and this method is actually needed to make fixed tabs, the Google ioshed version is more updated and so we are going to use that. Along with the SlidingTabLayout.java we would be needing the SlidingTabStrip.java, Okay so let's start making the Sliding Tabs.


Requirements


1. Android Studio 1.0.1 (latest)

2. SlidingTabLayout.java & SlidingTabStrip.java from IOsched Google App and copy past both the files in your project

Understanding Sliding Tab Layout Implementation





As you can see we have we have made the Linear Layout as the root element for our activity and made the orientation of the LinearLayout as vertical so the elements would be placed one after another, First I have added the toolbar on which I have already made a separate tutorial on how to make a material design toolbar, Next element that I have added is the SlidingTabLayout which acts like a Tab Strip, you can place this strip anywhere in your layout but I want it to be above the pages that are being swiped so I am placing it just below the Toolbar, Next you add the View Pager which is required for swiping the pages. In the code you define every view and then set the SlidingTabs.SetViewPager method to the ViewPager in your activity which is where you tell the app that on page swipe of your View Pager you want the tabs to swipe and change as well.



Steps To Implement Sliding Tab Layout


1. First let's decide the color scheme for our app I want the color scheme to be red so lets do that by making a new color.xml file in your values folder and add the following code to it. You may notice a item in the color.xml with name ScrollColor that is the color which I am going to set to the scroll bar of the Tab Strip.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="ColorPrimary">#e62117</color>
    <color name="ColorPrimaryDark">#c31c13</color>
    <color name="tabsScrollColor">#8a140e</color>

</resources>


2. Next we need to make a layout file for toolbar and add that layout file to our apps activity_main.xml. So create a new layout file and name it tool_bar.xml and add the following code to it.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:background="@color/ColorPrimary"
    android:elevation="2dp"
    android:theme="@style/Base.ThemeOverlay.AppCompat.Dark"
    xmlns:android="http://schemas.android.com/apk/res/android" />

3. Now its time to add Toolbar and the SlidingTabLayout to our main_activity.xml, To add SlidingTablayout in your app you must make sure you have already added the SlidingTabLayout.java and SlidingTabStrip.java in your app as explained in the requirements section at the top. If you have added both the files in your project, open your main_activity.xml and add the following code to it. I have given the SlidigTabLayout an id ="Tabs" and added a elevation of 2dp for the shadow effect.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        />

    <com.android4devs.slidingtab.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="2dp"
        android:background="@color/ColorPrimary"/>

</LinearLayout>  

4. Now we just have to add the ViewPager view to your layout, make sure to give it an Id, I have given my ViewPager an Id called pager. Finally your main_activiy.xml looks something like this.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        />

    <com.android4devs.slidingtab.SlidingTabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="2dp"
        android:background="@color/ColorPrimary"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"

        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_weight="1"
        ></android.support.v4.view.ViewPager>



</LinearLayout>

5. Now I have decided to make 2 tabs for this project, so I have to make the layout for this tabs, so I have created two new layouts tab_1.xml and tab_2.xml and added the medium text view inside both the layout as shown below.

tab_1.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="You Are In Tab 1"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

tab_2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="You Are In Tab 2"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Now I am done with my layout section and its time to work things out in the code.

6. Now let's first make the 2 fragments for Tab1 and Tab2, So go ahead and create two new java files, name it Tab1 and Tab2 and add the following code to it.

Tab1


package com.android4devs.slidingtab;

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

/**
 * Created by hp1 on 21-01-2015.
 */
public class Tab1 extends Fragment {

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


Tab2


package com.android4devs.slidingtab;

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

/**
 * Created by hp1 on 21-01-2015.
 */
public class Tab2 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab_2,container,false);
        return v;
    }
}


7. Now before we start working with MainActiviy we need a ViewPager adapter to provide the views for every page i.e every Tab. So go ahead and make a new java file, name it ViewPagerAdapter and add the following code to it. I have added the comments to help you understand the working.

package com.android4devs.slidingtab;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

/**
 * Created by hp1 on 21-01-2015.
 */
public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
    int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


    // Build a Constructor and assign the passed Values to appropriate values in the class
    public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
        super(fm);

        this.Titles = mTitles;
        this.NumbOfTabs = mNumbOfTabsumb;

    }

    //This method return the fragment for the every position in the View Pager
    @Override
    public Fragment getItem(int position) {

        if(position == 0) // if the position is 0 we are returning the First tab
        {
            Tab1 tab1 = new Tab1();
            return tab1;
        }
        else             // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
        {
            Tab2 tab2 = new Tab2();
            return tab2;
        }


    }

    // This method return the titles for the Tabs in the Tab Strip

    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

    // This method return the Number of tabs for the tabs Strip

    @Override
    public int getCount() {
        return NumbOfTabs;
    }
}


8. Now we have everything ready to start work with the MainActivity.java, So go ahead and add the following code to your MainActivity.java. check out the comments in the code to understand the working.

package com.android4devs.slidingtab;

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


public class MainActivity extends ActionBarActivity {

    // Declaring Your View and Variables

    Toolbar toolbar;
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[]={"Home","Events"};
    int Numboftabs =2;

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


        // Creating The Toolbar and setting it as the Toolbar for the activity

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


        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);



    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


Now everything is set, Lets just run our app and check out how it looks



Its Looks perfect. Tabs are working nicely. But what if you want to customize the text color of your Tabs Title for a specific event i.e on Page selected etc and you surely would like to tell the user about the active tab he is on. For this you have to make a selector.xml in  your res/color/ folder and add the following code to your selector.xml, of course change the colors as your requirements

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:color="@android:color/white" />
    <item android:state_focused="true" android:color="@android:color/white" />
    <item android:state_pressed="true" android:color="@android:color/white" />
    <item android:color="#8a140e" />
</selector> 

After making the selector you have to add it in your SlidingTabLayout.java, Look for a method called  private void populateTabStrip() and add the following line of code at the end of it.

tabTitleView.setTextColor(getResources().getColorStateList(R.color.selector));
tabTitleView.setTextSize(14);


Look at the SlidingTabLayout code below, I have just copy pasted populateTabStrip() method in which you are suppose to do the changes

private void populateTabStrip() {
        final PagerAdapter adapter = mViewPager.getAdapter();
        final View.OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (mTabViewLayoutId != 0) {
                // If there is a custom tab view layout id set, try and inflate it
                tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
                        false);
                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            if (mDistributeEvenly) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                lp.width = 0;
                lp.weight = 1;
            }

            tabTitleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);
            String desc = mContentDescriptions.get(i, null);
            if (desc != null) {
                tabView.setContentDescription(desc);
            }

            mTabStrip.addView(tabView);
            if (i == mViewPager.getCurrentItem()) {
                tabView.setSelected(true);
            }
            tabTitleView.setTextColor(getResources().getColorStateList(R.color.selector));
            tabTitleView.setTextSize(14);
        }
    }


Finally, Everything is set and we are done. Let's just run the app and check out how things work.



Well that's just looks amazing, So with this you have learned how to make Sliding Tabs in Material Design style, If you like this tutorial please subscribe to the blog for coming updates.

Akash Bangad

Computer Engineer from Maharashtra,India. Trying to make my way in the world of mobile development. Steve Jobs admirer and techy at heart.

234 comments:

  1. Thanks man!
    Your tutorial was very helpfull for me! Very clear and accurate.

    Thanks again!

    ReplyDelete
    Replies
    1. if your project is working fine, please share it with me please
      Email : Umair_softengr@yahoo.com

      Delete
  2. Thank you so much! Great tutorial.

    ReplyDelete
    Replies
    1. if your project is working fine, please share it with me please
      Email : Umair_softengr@yahoo.com

      Delete
  3. Thanks a lot !
    Great tutorial, very helpful and brightly made !

    ReplyDelete
    Replies
    1. if your project is working fine, please share it with me please
      Email : Umair_softengr@yahoo.com

      Delete
  4. Awesome tutorial, thanks! :-) .... Could be next lesson open new activity (this 2-tab activity) from left drawer from previous tutorial? ;-)

    ReplyDelete
  5. Great tutorial. Thanks. Taking in account that Pre-Lollipop doesn't allow properties like 'android:elevation="2dp"', what is the best way to simulate it for API lower than 21?

    Thanks.

    ReplyDelete
    Replies
    1. i guess you can use shadows, which can be abit tricky :D

      Delete
  6. You made very usefull tutorial! Thanks!

    ReplyDelete
    Replies
    1. if your project is working fine, please share it with me please
      Email : Umair_softengr@yahoo.com

      Delete
  7. Replies
    1. if your project is working fine, please share it with me please
      Email : Umair_softengr@yahoo.com

      Delete
  8. This was exactly what I was looking for, Thanks! I seem to be having some errors tho, is there anyway I could get the source code? :D

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. For some reason my app would not work and always crashes moment I launch it. I followed the tutorial and restarted the app thee times from scratch and still would not work. Is there something I should change that you haven't mentioned in the tutorial? Please let me know. thanks.

    ReplyDelete
    Replies
    1. If you are using AppCompat, in styles.xml put this line
      false

      Delete
    2. Hey ! Facing the same problem. Did you find any solution?

      Delete
    3. in main_activity.xml change com.android4devs.slidingtab to your package name

      Delete
    4. This comment has been removed by the author.

      Delete
    5. Changes to be made:
      In main_activity.xml
      Change com.android4devs.slidingtab to your package name.

      In style.xml
      item "windowActionBar" as false
      item "windowNoTitle" as true

      Delete
  11. My app created jst lyk above procedure doesnt opens, force stops while opening itself. Any idea sir?

    ReplyDelete
    Replies
    1. in main_activity.xml change com.android4devs.slidingtab to your package name

      Delete
    2. @mehviish I tried the change, my app still crashes. all code is same to same, please help

      Delete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Hi Akash,

    Thanks for the tutorial. Is there anyway I can add badge to tabs to show users count?

    ReplyDelete
  14. Awesome tutorial! Thanks man! Happy coding!! ;D

    ReplyDelete
  15. I got an Error " HorizontalScrollView can host only one direct child"

    ReplyDelete
  16. Hi
    Please tell me if it's work for API 16 (android 4.1.2) thank you

    ReplyDelete
  17. Thanks a lot, especially for the part about coloring text in tabs!

    ReplyDelete
  18. Hey I loved your tutorial and thanks for your effort. I just have one error in the ViewPagerAdapter Class of the public fragment getItem method. the error is about returning the tab1 and i don't know how to get my head round it. the error states "Incompatible type: Required: android.support.v4.app.Fragment
    Found: com.slidingtoolbar.Tab1"

    ReplyDelete
    Replies
    1. Tab1 needs to extend android.support.v4.app.Fragment class

      Delete
  19. This comment has been removed by the author.

    ReplyDelete
  20. Thanks and love your tutorial.... Finally I able to create this design based on your tutorial.... Thank you very much... Would like to see more of your tutorial!!!

    ReplyDelete
  21. Wondering is it possible for you to provide some tutorial for the animations?

    ReplyDelete
  22. Hi Akash,

    Thank you for the tutorial!

    I have an issue, I need to use the OnResume(); method in my fragments, but when I switch between the tabs, the method isn't called, could you help me please?

    Thanks!

    ReplyDelete
    Replies
    1. I found the answer:

      http://stackoverflow.com/questions/10024739/how-to-determine-when-fragment-becomes-visible-in-viewpager

      Delete
  23. This comment has been removed by the author.

    ReplyDelete
  24. This comment has been removed by the author.

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. Hi Akash. Thanks for great tutorial.
    I just have an improvement. Instead of modifying SlidingTabLayout.java to set text color and size you can use setCustomTabView method.

    mTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);

    tab_indicator layout:

    TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:background="?android:selectableItemBackground"
    android:layout_width="wrap_content"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:layout_height="48dp"
    android:gravity="center"
    android:textColor="@color/selector"
    android:textSize="14sp"
    android:textStyle="bold"
    android:fontFamily="@string/font_fontFamily_medium"
    android:textAllCaps="true"

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. I have copy pasted the entire code in my Android studio. No errors during build.
    Whenever I run the app, it crashes even before it opens.

    Please help.

    ReplyDelete
    Replies
    1. Change the package name in activity_main.xml to your package name.

      In style.xml add
      item name="windowActionBar" as false
      item name="windowNoTitle"as true

      You have to make color directory. Inside that you have to paste the selector file.

      Delete
  29. Tabs are not visible in my app but sliding functionality is working.

    please do help

    ReplyDelete
  30. How can I decrease the tab size?

    ReplyDelete
  31. This comment has been removed by the author.

    ReplyDelete
  32. Thank you so much. Very neat explanation & your tutorial has helped me a lot in making tabs :-) God bless u :-D Keep coding :-) Arigato Gozaimasu.

    ReplyDelete
  33. This Tutorial Was damn Good .I need the same integrated in NAvigation drawer.Can you please

    ReplyDelete
    Replies
    1. I used these tabs with a navigation drawer. I can send you the code if you want..

      Delete
    2. Can you please send it to me?

      Delete
    3. This comment has been removed by the author.

      Delete
    4. I also want to integrate this code in Navigation Drawer.. do you know how?

      Delete
    5. I also want to integrate the sliding tab thing in Navigation drawer. Please can you send me the code?

      Delete
  34. Hello.

    I have 3 tabs and each goes into a separate detail activity.

    However if I press the back button it always goes to the first tab, instead of the tab that started the activity.

    Is there a way to go to a certain tab programatically? I'm thinking of storing the tab # , and after pressing the back button calling a goToTab(number) (for example) to return to that tab and not the starting activity which contains the tabs.

    ReplyDelete
    Replies
    1. Can i get the answer for this? I also want to do this.

      Delete
  35. This comment has been removed by the author.

    ReplyDelete
  36. I am novice into android..
    I am getting eroor at : android:theme="@style/Base.ThemeOverlay.AppCompat.Dark"
    -- No resource found that matches the given name

    ReplyDelete
  37. how should i do this step?
    2. SlidingTabLayout.java & SlidingTabStrip.java from IOsched Google App and copy past both the files in your project
    Should i create a class and copy the codes ?

    ReplyDelete
    Replies
    1. yes!Create this classes and just copy&paste them

      Delete
  38. This comment has been removed by the author.

    ReplyDelete
  39. Hi. i have a problem when i try create 5 tabs with table layouts inside them. First, the 3rd table returns null on findviewbyid. And second when i implement only the first two tabs and click on the 3rd one the first tab looses its contents. Any idea about this?

    ReplyDelete
    Replies
    1. fix this. i should set setOffscreenPageLimit(5) for 5 tabs...:)

      Delete
  40. Hi men i have an error when launch the app. "This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead."

    ReplyDelete
    Replies
    1. The answer is on his previous Toolbar tutorial and I quote:
      "3. Even though ActionBars are replaced by App bar/Toolbar we can still use ActionBar, but in our case we are going to make a Toolbar so go to your style.xml and change the theme to "Theme.AppCompat.Light.NoActionBar, This helps us get rid of the ActionBar so we can make a App bar."

      Delete
  41. This comment has been removed by the author.

    ReplyDelete
  42. Hi
    can you help me?
    I want display tab in fragment.
    i do but it not display.
    this is HomeFragment
    http://i.imgur.com/ckcgDTU.jpg

    ReplyDelete
  43. This comment has been removed by the author.

    ReplyDelete
  44. Hi

    First Thank you men!!!
    Second How to change the background color of SlidingTabLayout by state "pressed, selected, unselected"? I'm try by hours but i can't make it works.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. if you want change text color of background tab, you can do this changing value of <item android:color="here" /> in res/color/selector.xml

      Delete
  45. Thanks for the good tutorial. You are the best :)

    ReplyDelete
  46. hey thank you for the awesome tutorial!! i did exactly as u told!! but wen i run it on ma phone, a message prompts saying app has unfortunately stopped ! if anyone has the app working perfectly!! plz do mail it to me!
    at lijodavidson@gmail.com
    thanks

    ReplyDelete
  47. Thanks for this good tutorial!! Great one!

    ReplyDelete
  48. hi, I followed this tutorial, everything works fine but when I use a listview into a slidingtab the text (in the listview) turns white whereas it was black... do you have an explanation

    ReplyDelete
  49. Hi, thanks for such a great piece of code. I implemented this in one of my project. However I am having an issue.

    I am showing three tabs. In one tab I am calling api and populating the data in listview. In second tab I am getting data from db and populating it in listview. In third tab I am showing list of contacts from phonebook. Now because these heavy computations on my main thread, the ViewPager is not scrolling fast and smoothly. Its lagging.

    How can I avoid it? When and how should I load and display data to make my ViewPager scroll like lightening?

    ReplyDelete
    Replies
    1. Hi, I also want to do something similar, can you help?
      Dear Author,
      Can you produce a tutorial for SlideTabs with ListView?

      Delete
  50. Good Tutorial!!

    I am having an issue here. "R.color.selector" is not working. It is added in drawable folder and can't be added in values folder.

    ReplyDelete
    Replies
    1. Oh! I have done it. You need to create "color" sub directory under "res" directory and then add "selector.xml" there. Thanks

      Delete
  51. Awesome tutorial. Congrats!

    I need to use these tabs with a navigation drawer. Do you have anything related to help me?
    Thanks!

    ReplyDelete
  52. Does this example works on pre lollipop devices. For lollipop devices it's working fine but on kitkat it's not

    ReplyDelete
  53. Hello,

    When I go landcape : it not work. I crreate a layout for a view specially to landscape mode and not use it ? Why ?

    ReplyDelete
  54. Hello people great guide. Thanks
    I have done everything as described but app crashes on every device where i tested.
    If someone could send me working code, that would be awesome! Thanks
    Oh mail is mile.vrtunic@gmail.com

    ReplyDelete
  55. Excuse me, I tried the codes above, but I got some error.
    Could you upload your whole project on the web ,please?
    Let's us download it!
    Thanks a lot.

    ReplyDelete
  56. hey,

    i want to make the textview of the selected tab bold like you did with the textColor, but i cant use a selector for that. do you know a way to that. making the selected tab textStyle Bold.

    ReplyDelete
  57. Hi Akash. Thank you for your great website.
    I would be honored if you can help me , how can I set swipe tabs slide right to left ?

    ReplyDelete
  58. Hey dude,

    I've got your example code up and running within my current app, it works great the first time around, but when navigating to another fragment and then back again the tab fragments are empty.

    Any ideas what might be causing this?

    ReplyDelete
  59. What should i write in Fragment getItem method if i want to add one more tab?

    Thank you for this tutorial.

    ReplyDelete
    Replies
    1. In your Fragment getItem change it to this:

      @Override
      public Fragment getItem(int i) {
      switch (i) {
      case 0:
      return new Tab1();
      case 1:
      return new Tab2();
      case 2:
      return new Tab3();
      case 3:
      return new Tab4();
      }
      return null;
      Make sure you add new Java,

      In your MainActivity change CharSequence and int Numboftabs to(or what ever you want):

      CharSequence Titles[]={"Home","Events","Test 1","Test 2"};
      int Numboftabs =4;

      Delete
  60. Thanks dude for the tutorial, but i'm facing little problem. The sliding tabs is too large in height (since use property wrap content) and its title for each tabs did not show.
    I have read your tutorial many times to see what I missed, but I couldn't find it.
    Can ou give me solution?

    Thank you very much.

    ReplyDelete
    Replies
    1. you can use improvements of "Roland Yeghiazaryan" http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html?showComment=1426238480095#c6242495915977088200

      I just have an improvement. Instead of modifying SlidingTabLayout.java to set text color and size you can use setCustomTabView method.

      mTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);

      tab_indicator layout:

      <TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@android:id/text1"
      android:background="?android:selectableItemBackground"
      android:layout_width="wrap_content"
      android:paddingLeft="16dp"
      android:paddingRight="16dp"
      android:layout_height="48dp"
      android:gravity="center"
      android:textColor="@color/selector"
      android:textSize="14sp"
      android:textStyle="bold"
      android:fontFamily="@string/font_fontFamily_medium"
      android:textAllCaps="true"/>

      change layout_height to "wrap_content" and add android:paddingBottom="you chose value"

      Delete
  61. how to use this tab view in a fragment....
    I want to use it with navigation drawer and i use a modules for navigation drawer ...
    please help me anyone........

    ReplyDelete
  62. hi!
    i successfuly do all this stuff but i gor a problemm, here is description:
    http://stackoverflow.com/questions/30647339/missing-slidingtablayout?noredirect=1#comment49393384_30647339

    will be glad any solutions!

    ReplyDelete
  63. Hello, how to se Tag for the each fragment?

    ReplyDelete
  64. hello, how to set tag for each fragment and get current visible fragment?

    ReplyDelete
  65. hello, have a source code ?

    ReplyDelete
  66. Hi, Fabulous tutorial. I have followed it step by step, and made it to the point where my code seems to have no errors, it compiles sweet. But as soon as I run it on emulator it crashes with the following message : "Unfortunately, Testing_sidebar has stopped" (Testing_sidebar is the name of the project) . COuld you help me with what would be the error ?

    ReplyDelete
    Replies
    1. In your activity_main.xml, try to rename <com.android4devs.slidingtab.SlidingTabLayout... with your own package name like this : <com.yourpackage.SlidingTabLayout...

      Delete
  67. Thank you so so much for this tutorial. It helped me out a lot. Works perfectly.

    ReplyDelete
  68. Hi faboulous tutorial nut i am facing an error while running the project. The error is below.

    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. I got the same problem, maybe you can check your layout, I solve it like this

      @Overrid
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout."YOUR_LAYOUT_NAME");
      ...
      }

      Delete
  69. great tutorial. how could I add images instead of text on the tab.??

    ReplyDelete
  70. This comment has been removed by the author.

    ReplyDelete
  71. This comment has been removed by the author.

    ReplyDelete
  72. Hi!

    Getting this error:
    "Unable to start activity ComponentInfo{name_of_app/name_of_app.MainActivity}: android.view.InflateException: Binary XML file line #68: Error inflating class fragment"

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. in activity_main.xml

      replace `com.android4devs.slidingtab` with your package name

      Delete
  73. I have a button on first tab and on click of that button I have to navigate to Tab2. How can I do that?

    ReplyDelete
  74. Dude cannot start activity from your fragment.....Guide us through...........

    ReplyDelete
  75. Dude cannot start activity from your fragment.....Guide us through...........

    ReplyDelete
  76. Dude cannot start activity from your fragment.....Guide us through...........

    ReplyDelete
  77. HI!! I want to draw a simple partition line between tabs. How I would be able to achieve this. Please help me.

    ReplyDelete
  78. Hi i have encountered error Unable to start activity ComponentInfo{com.cap2.macsanity.droidgency/com.cap2.macsanity.droidgency.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class how to fix this? please help me

    ReplyDelete
  79. Why do have to use external library to have swipe effect? Is there any way to use tablayout directly with all functionalities by using the support library itself?

    ReplyDelete
  80. I using sliding tabs in setting screen of live wallpaper using Fragment Activity and it have tabs but swiping doesn't work perfectly. I have total 3 tabs and have to swipe 6-7 times to reach to 3rd tab through swipe. can you please help?? Min api version is 9 and max api is 22

    ReplyDelete
  81. saya mendapatkan error pada saat run
    warning : the project encoding (windows-1252) does not match the encoding specified in the gradle build files (UTF-8)

    ReplyDelete
  82. This Tutorial was good. Can we integrate navigation drawer to this ?

    ReplyDelete
  83. This comment has been removed by the author.

    ReplyDelete
  84. Please Help...
    I got Rendering error when i try to create tool_bar.xml

    "Rendering Problems The following classes could not be found:
    - android.support.v7.widget.Toolbar (Fix Build Path, Create Class)
    Tip: Try to build the project. "
    How to solve this error I tried alot.
    Dont tell me to move on lower API

    ReplyDelete
  85. Hi, thanks for this tutorial, with the help of this am learning the concept of SlidingTabs using view pager, once am implemented am get the issues on following lines

    if (mDistributeEvenly) {
    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
    // lp.width = 0;
    // lp.weight = 1;
    }

    Once am comment the width and weight means am able to run it and the tabs are displayed nearby each other not as like as it fit for the screen because of the weight am comment it.Will you please guide me how to rectify this.

    ReplyDelete
    Replies
    1. if you want both centered just set mDistributeEvenly to true (OR comment out the "if(mDis...)" lp.weight needs to be 1 that both textviews will use the space they can fill.
      ----TAB 1---- | ----TAB 2---- // <- result when weight is set
      TAB1 | TAB2 // <- result if NOT
      Hope that make sense? :)

      Delete
  86. Can you share a working project to abhimaliyeckal@gmail.com plz ?
    any help appreciated :)

    ReplyDelete
  87. Hi, i've my shared my code via mail, thanks

    ReplyDelete
  88. How to Add sliding tab in Naviagation

    ReplyDelete
  89. hi, is it able to add images in the place of tabs heading section

    ReplyDelete
  90. Hi there i put listview in tab1 which is Newsfeed in my code. the problem is its showing the Newsfeed not my tab2 which is Inbox here is my codes pls help me

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

    listView = (ListView) getActivity().findViewById(R.id.list);

    feedItems = new ArrayList<>();

    listAdapter = new FeedListAdapter(getActivity(), feedItems);
    listView.setAdapter(listAdapter);


    // new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    // We first check for cached request
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Cache.Entry entry = cache.get(URL_FEED);
    if (entry != null) {
    // fetch the data from cache
    try {
    String data = new String(entry.data, "UTF-8");
    try {
    parseJsonFeed(new JSONObject(data));
    } catch (JSONException e) {
    e.printStackTrace();
    }
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }

    } else {
    // making fresh volley request and getting json
    JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
    URL_FEED, null, new Response.Listener() {

    @Override
    public void onResponse(JSONObject response) {
    VolleyLog.d(TAG, "Response: " + response.toString());
    if (response != null) {
    parseJsonFeed(response);
    }
    }
    }, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
    VolleyLog.d(TAG, "Error: " + error.getMessage());
    }

    });

    // Adding request to volley request queue
    AppController.getInstance().addToRequestQueue(jsonReq);

    v.bringToFront();

    }return v;

    }

    /**
    * Parsing json reponse and passing the data to feed view list adapter
    * */
    private void parseJsonFeed(JSONObject response) {
    try {
    JSONArray feedArray = response.getJSONArray("feed");

    for (int i = 0; i < feedArray.length(); i++) {
    JSONObject feedObj = (JSONObject) feedArray.get(i);

    FeedItem item = new FeedItem();
    item.setId(feedObj.getInt("id"));
    item.setName(feedObj.getString("name"));

    // Image might be null sometimes
    String image = feedObj.isNull("image") ? null : feedObj
    .getString("image");
    item.setImge(image);
    item.setStatus(feedObj.getString("status"));
    item.setProfilePic(feedObj.getString("profilePic"));
    item.setTimeStamp(feedObj.getString("timeStamp"));

    // url might be null sometimes
    String feedUrl = !feedObj.isNull("url") ? feedObj
    .getString("url") : null;
    item.setUrl(feedUrl);

    feedItems.add(item);
    }

    // notify data changes to list adapater
    listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
    e.printStackTrace();
    }

    ReplyDelete
  91. where to set mTabViewLayoutId? I want to have a layout at tab

    ReplyDelete
  92. really nice tutorial , please tell me how to change the height of sliding tab strip

    ReplyDelete
  93. how can i use customtabs with two textviews in vertical .... i have provieded id of layout but still it showing me one textview in tabs

    ReplyDelete
  94. Hello all,

    this tutorial works well on lollipop devices, but on pre-lollipop devices i cant move to next tab after click on tab name, only way how to move to next tab is swipe. So please can anyone tell me how to make tab names clickable on pre-lollipop? Thanks in advance.

    Honza

    ReplyDelete
  95. This comment has been removed by the author.

    ReplyDelete
  96. Spend a whole day , and not working at all!

    ReplyDelete
  97. Awesome tutorial , thanks a lot !
    But there are some problems with the "Subscribe System", I couldn't receive any Confirm E-mail after subscribed.(foxmail)

    ReplyDelete
    Replies
    1. Hello your project with this article it working if working please send me the project simple. thank u

      Delete
  98. Thanks Dude !!!
    Really Helpful, You Saved me. I was in trouble from two days.

    ReplyDelete
    Replies
    1. Hello!! if your project is working fine, please share it with me please
      Email :vongchamnanz@gmail.com

      Delete
  99. Hey guys. Is there a way of knowing what tab we are on from Main activity? Because I want some FAB animations.

    ReplyDelete
  100. Thanks, very clear, very detailed.

    ReplyDelete
    Replies
    1. Hello your project with this article it working if working please send me the project simple. thank u

      Delete
  101. Wow!! Now I can do it complete Thank q so much.
    So I have one quest to ask :

    how to add Icon to each Tab??

    Please feedback to me : vongchamnanz@gmail.com

    ReplyDelete
  102. Hey i know this is a bit late but I'm getting an error. So when i try to have more than two tabs like for say a 3rd tab if i swipe to anything other than the first tab , the tab will load then after its finish loading it will crash with a .NullPointerException I can't seem to figure out what i may have missed.

    ReplyDelete
  103. Dear Author,
    Can you produce a tutorial for Swipe tabs with ListView?

    ReplyDelete
  104. How to set Icons instead of tab name??

    ReplyDelete
  105. Very nice and helpful tutorial. But I have a problem using this. It seems that If lets say we have more than 2 tabs, and we want to refresh them, when you go from A to B and back to A it is not refreshed cause the ViewPager uses pipeline. Do you have any suggestions?

    ReplyDelete
  106. getting error the activity already has an action bar supplied by window decor do not request window.Feature_Action_Bar and set Window action bar as false

    ReplyDelete
  107. Hello i included my package name as well as i included the item name in my styles.xml file but my app crashes on launch. Please provide me solution asap

    ReplyDelete
  108. Only creates an instance two fragments at a time , then press the other when going moving , how to increase ?

    ReplyDelete
  109. Only creates an instance two fragments at a time , then press the other when going moving , how to increase ?

    ReplyDelete
  110. Instead of titles, I wanna show icon images as titles like in facebook in the SlidingTabLayout title, how to do that??

    ReplyDelete
  111. Hi
    Very great tut , very clear explannation.
    I want to know if it will work for android min SDK = 10?

    ReplyDelete
  112. Now can you help me to make a click event for a button which is inside tab_1.xml or tab_2.xml ?
    Awesome tutorial it was.

    ReplyDelete
  113. It's a Wonderful tutor...
    I have four Tabs like A,B,C and D
    a ViewPager loads the next view so that it is ready when you want to scroll to the next fragment. by default the viewpager loads the previous current and next fragment in the ViewPager so when you scroll from A to B, C is going to be loaded in so that you have a smooth scroll when you go to C

    But My C Fragment's input is come after update the B Fragment So, C Frgament's OnCreate Doesn't work again.. Do you have any idea to do that? Please share with me...
    Thanks

    ReplyDelete
  114. thanks dear but asked you one thing more how to change tabs name or text with icons on the tabs??

    ReplyDelete
  115. hi...
    Nice tutorials...
    Bt How to change sliding tab text color when its click?i am using populateTabStrip() in my code but its not work.
    Thank you

    ReplyDelete
  116. Hi
    i have a couple of problems,

    The first one is about the menu_main. I didnt have that so i created one in the menu folder, but empty must i put something in there?

    The other problem is about the R.id.action_settings, there is no id with that name, so i created in a folder called ids




    ofc it didnt worked. What i have to do¿
    My app just say that unfortunately the app ahs stopped.

    Do you need more info to tell me what is wrong? just tell me.

    Thank you so much in advance!
    Regards

    ReplyDelete
    Replies
    1. okey
      i put something like this:


      inside menu_main.xml and the problem disappear but it still is saying that unfortunately the app has stopped idk where is the problem :(

      Delete
    2. Just remove the lines showing the errors. You don't need them.

      Delete
    3. what do you mean?
      remove this:

      override
      public bolean...
      (R.menu_menumain..)
      ...

      and

      public bloean
      int id = item.getitemid..

      if (id == action.settings)...
      ...

      Delete
  117. Bro,

    You really rock! I removed some things such as the toolbar, as it was taking some extra space and honestly the tutorial is really good!

    Thanks a lot!

    ReplyDelete
  118. Rendering Problems The following classes could not be found:
    - com.android4devs.slidingtab.SlidingTabLayout (Fix Build Path, Create Class)
    Tip: Try to build the project.

    Please help me

    ReplyDelete
    Replies
    1. In activity_main.xml replace "com.android4devs.slidingtab.SlidingTabLayout" with the path to your class.

      Delete
  119. This comment has been removed by the author.

    ReplyDelete
  120. can u please send me zip file to me this example pavansiva999@gmail.com

    ReplyDelete
  121. Thank You!! This was awesome (y)

    ReplyDelete
  122. This comment has been removed by the author.

    ReplyDelete
  123. This comment has been removed by the author.

    ReplyDelete
  124. hi, how can i do this in only one half of the screen,,like the bottom side,,and the top i will have other stuff like images that the user can change when he presses the right or left button, and the slide tabs should be on the other half....

    ReplyDelete
  125. Hey, everything works perfect but where the colorprimarydark is implemented? My upper side of page still looks gray(where the phone icons stay) Also, getcolorstatelist(int id) is deprecated do you have any alternative for that? Thank you so much.

    ReplyDelete
  126. how can i import SlidingTabLayout in android studio

    ReplyDelete
  127. hello,
    i wanna start tabs from right for arabic language(right align) (in ordinary situation there start from left)

    any body can help me please :)

    ReplyDelete
  128. Thanks! But how can i change the color of tabs strip?

    ReplyDelete
  129. Hi,if your project is working fine, please share it with me please Email :jonewonewtest@gmail.com Thank You.

    ReplyDelete
  130. Thank you so much! Muito obrigado!

    ReplyDelete
  131. Very helpful.
    Made my work so much faster.

    ReplyDelete
  132. thanks.......waiting for more tutorial

    ReplyDelete
  133. can I have anyone working project. I would really appreciate that
    khairulizha95@gmail.com

    ReplyDelete
  134. Can u please update its manifest.xml file, coz getting an errors of unfortunate application stopped.

    ReplyDelete
  135. Hi, why i have this problem on MainActivity?

    http://i.imgur.com/D6II83p.png

    ReplyDelete
  136. Hi ,

    I have used your code to show different fragment in home page with one addition of navigation drawer.
    I want to open different fragment/ view in navigation drawer on home page.
    Please suggest me the way to open different view in the navigation drawer based on view pager position.

    ReplyDelete
  137. Hey! Gr8 tutorial. It's working very fine for me.
    So now I want to add recyclerView under the tabs. Can you or anybody can help me with this? I want to know how to implement recyclerview inside fragments.
    Thanks

    ReplyDelete
  138. how to add icon to these tabs

    ReplyDelete
  139. I'm having trouble with only one part but I can't seem to fix/solve it, its on the MainActivity with the getMenuInflater().inflate(R.menu.menu_main, menu); and R.id.action_settings (i.e last two methods of MainActivity). I don't have a res/menu file.
    Does anyone how to fix this or info on what to place in the menu.xml file?

    ReplyDelete
  140. I'm having trouble with only one part but I can't seem to fix/solve it, its on the MainActivity with the getMenuInflater().inflate(R.menu.menu_main, menu); and R.id.action_settings (i.e last two methods of MainActivity). I don't have a res/menu file.
    Does anyone how to fix this or info on what to place in the menu.xml file?

    ReplyDelete
  141. hey, I have a problem in ViewPagerAdapter. error in "return tab1" and "return tab2" which is position value. It shown as incompatible types.

    ReplyDelete