Android sliding tabs example

We all know what is tabview . If we want to display multiple screens in a same activity in android we will use tabview. If you are not familiar with the concept of tabview please refer Android viewpager with tabs example and Android cardview with tabview example in which you will find the basic example for implementing a tabview in android. But in some cases there is a possibility that number of tabs will be high that it will be difficult to fit in android phones screen. For solving this problem we can use a SlidingTabLayout view which is custom view of tab layout in android. In this tutorial we will learn how to implement sliding tabs in android.

Steps

  1. Create a new project in android studio
  2. Download the SlidingTabLayout.java and SlidingTabStrip.java and place it on your project
  3. Creating layouts for number of tabs you required
  4. Implementing fragment classes for all the tabs you created
  5. Create the code for the sliding tab layout in you activity’s layout file
  6. Implement the code for tab and viewpager in your activity file

Create New project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

Download the required files

For implementing this example you need to have updated code of the following files which will be available at developers page.

After downloading this files you need to place both files under java/src/your package/

Creating layouts for number of tabs you required

This is an example of displaying3 tabs.So there will be three fragments and there will be respective layouts for each fragments.So first step is to create 3  files under res/layout/ and name it as tab1.xml ,tab2.xml,tab3.xml

Following is the code for tab1.xml,tab2.xml,tab3.xml(You can give your own content for respective tabs.Here i am using the same content)

<?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"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_tab1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Tab 1"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

Implementing fragment classes for all the tabs you created

Next step is to create three fragments under java/your package/ and name its as Tab1.java,Tab2.java,Tab3.java

Tab1.java

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

public class Tab1 extends Fragment {

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

//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.tab1, container, false);
}
}

Tab2.java

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

public class Tab2 extends Fragment {

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

//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
 return inflater.inflate(R.layout.tab2, container, false);
 }
}

Tab3.java

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

public class Tab3 extends Fragment {

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

//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
 return inflater.inflate(R.layout.tab3, container, false);
 }
}

Create the code for the sliding tab layout in you activity’s layout file

A layout file will be automatically created while you are doing this as new project ,if not right click on res->layout folder and click on New -> Layout resource file. Now add the following code in to the XML file created . The file will be having a layout which contains a sliding tab layout and a view pager.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.yourpackage.SlidingTabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:tabIndicatorHeight="1dp" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tabLayout" />
</RelativeLayout>

Now you need to create a selector.xml file under res/color/ folder which is using in SlidingTablayout.java for deciding the tablayout colors.

selector.xml

<?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="#FFFFFF" />
</selector>

Now add the following color to your colors.xml file. This is the color code which will decide your tab highlighting line colour.

<color name="tabsScrollColor">#FFC107</color>

Next step is to create an adapter class in java/yourpackage/

MainViewPagerAdapter.java

public class MainViewPagerAdapter 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 MainViewPagerAdapter(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 if(position == 1) // if the position is 1 we are returning the Second tab
{
Tab 2 tab2 = new Tab2();
return tab2;
}else if(position == 2) // if the position is 2 we are returning the third tab
{
Tab3 tab3 = new Tab3();
return tab3;
}
}

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

Implement the code for tab and viewpager in your activity file

Now finally implement the code for your activity’s java file.

public class MainActivity extends AppCompatActivity {

    private SlidingTabLayout tabLayout;
    private ViewPager viewPager;
    private MainViewPagerAdapter viewPagerAdapter;
    CharSequence Titles[]={"Tab1","Tab2","Tab3"};
    int Numboftabs = 3;

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


    private void init() {

        tabLayout = (SlidingTabLayout) findViewById(R.id.tabLayout);
        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPagerAdapter =  new MainViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
        viewPager.setAdapter(viewPagerAdapter);

        tabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }

            @Override
            public int getDividerColor(int position) {
                return 0;
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabLayout.setViewPager(viewPager);


    }

}

Now run the code you will be getting the following output

viewpage with tabs

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *