Today I’m talking about TabLayout.

TabLayout provides a horizontal layout to display tabs.
tab_layout_demo_app
STEP 1: ADD LIBRARY TO THE PROJECT
Firstly need to add library to gradle file for a project.

dependencies {
    compile 'com.android.support:design:22.2.0'
}

STEP 2: ADD COLORS AND STRINGS TO THE PROJECT
This project will contain static colors and strings. Better way store these datas in strings.xml and colors.xml files.
Firstly need to create colors.xml in res/values/ folder. Source code of this file will be next

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primaryColor">#2196F3</color>
    <color name="primaryColorDark">#1976D2</color>
    <color name="cyan">#00BCD4</color>
    <color name="teal">#009688</color>
    <color name="amber">#FFC107</color>
</resources>

Next step update strings.xml file in folder /res/values/. Need to add 3 string constants.

<string name="first">First</string>
<string name="second">Second</string>
<string name="third">Third</string>

STEP 3: UPDATE THEME FOR THE PROJECT
Need to update theme for whole application. You can find theme in file styles.xml in /res/values/ folder.

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/primaryColor</item>
        <item name="colorPrimaryDark">@color/primaryColorDark</item>
        <item name="colorAccent">@android:color/white</item>
    </style>
</resources>

STEP 4: UPDATE LAYOUT FOR ACTIVITY
Activity in this application show toolbar, tab layout and fragments. Layout call activity_main.xml you can find in res/layouts/ folder.

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

    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

Also you can have different style of tabs. For it you can change properties tabMode and tabGravity.
tab_properties

STEP 5: UPDATE ACTIVITY
Need to update our activity and create required tabs. For each tab need to create fragment. We will use the almost the same fragment. Each fragment will contain different color and text. Source code of activity will be next.

public class MainActivity extends AppCompatActivity {

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

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        TabLayout mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
        ViewPager mViewPager = (ViewPager) findViewById(R.id.viewPager);

        setSupportActionBar(mToolbar);
        setupViewPager(mViewPager);
        mTabLayout.setupWithViewPager(mViewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.add(getResources().getString(R.string.first), getResources().getColor(R.color.cyan));
        adapter.add(getResources().getString(R.string.second), getResources().getColor(R.color.teal));
        adapter.add(getResources().getString(R.string.third), getResources().getColor(R.color.amber));
        viewPager.setAdapter(adapter);
    }
}

STEP 6: CREATE ADAPTER FOR FRAGMENTS
Need to create adapter for application. This adapter will store information about fragments and their titles.

static class ViewPagerAdapter extends FragmentPagerAdapter {
    private List mFragmentList = new ArrayList<>();
    private List 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 add(String title, int color) {
        Fragment fragment = DummyFragment.newInstance(title, color);
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

STEP 7: ADD LAYOUT FOR FRAGMENT
Need to create simple layout for fragment which can change color of layout and text.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frameLayout">

    <TextView
        android:id="@+id/textView"
        android:text="item"
        android:textSize="36sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
</FrameLayout>

STEP 8: UPDATE FRAGMENT
Finally need to update fragment.

public static class DummyFragment extends Fragment {
    public static final String COLOR = "color";
    public static final String TEXT = "text";

    public static Fragment newInstance(String text, int color) {
        DummyFragment f = new DummyFragment();
        Bundle args = new Bundle();
        args.putInt(COLOR, color);
        args.putString(TEXT, text);
        f.setArguments(args);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.frameLayout);
        TextView textView = (TextView) view.findViewById(R.id.textView);
        frameLayout.setBackgroundColor(getArguments().getInt(COLOR));
        textView.setText(getArguments().getString(TEXT));
        return view;
    }
}

After run of project you show next application.
tab layout demo

This project you can find on github.

6 CommentsClose Comments

6 Comments

  • Hugo
    Posted August 10, 2015 at 10:04 pm 0Likes

    Is it possible that the viewpager is not swipeable?

    • Posted August 11, 2015 at 5:21 am 0Likes

      As I know you view pager swipeable, but you can create own viewPager like this.

      public class NonSwipeableViewPager extends ViewPager {
      
          public NonSwipeableViewPager(Context context) {
              super(context);
          }
      
          public NonSwipeableViewPager(Context context, AttributeSet attrs) {
              super(context, attrs);
          }
      
          @Override
          public boolean onInterceptTouchEvent(MotionEvent event) {
              return false;
          }
      
          @Override
          public boolean onTouchEvent(MotionEvent event) {
              return false;
          }
      }
      
  • amirj18
    Posted September 2, 2016 at 5:46 pm 0Likes

    hi,
    how can i set an animation for viewPager?!

  • ahmet
    Posted September 2, 2016 at 6:25 pm 0Likes

    hello my friend,
    can u tell me how to access fragment 2 or fragment 3 to create card view in them?

    • Posted September 18, 2016 at 8:44 pm 0Likes

      In my case I use just one fragment but with different data. This source code it’s a part of example app:
      public static class DummyFragment extends Fragment {

      public static final String COLOR = “color”;
      public static final String TEXT = “text”;

      public static Fragment newInstance(String text, int color) {
      DummyFragment f = new DummyFragment();
      Bundle args = new Bundle();
      args.putInt(COLOR, color);
      args.putString(TEXT, text);
      f.setArguments(args);
      return f;
      }

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragment, container, false);
      FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.frameLayout);
      TextView textView = (TextView) view.findViewById(R.id.textView);
      frameLayout.setBackgroundColor(getArguments().getInt(COLOR));
      textView.setText(getArguments().getString(TEXT));
      return view;
      }
      }

      However you can add different fragment in your ViewPagerAdapter.
      static class ViewPagerAdapter extends FragmentPagerAdapter {

      public void add(String title, int color) {
      Fragment fragment = DummyFragment.newInstance(title, color);
      mFragmentList.add(fragment);
      mFragmentTitleList.add(title);
      }
      }

      And finally you setup and display some data from your Activity or Fragment:
      ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
      adapter.add(getResources().getString(R.string.first), getResources().getColor(R.color.cyan));
      adapter.add(getResources().getString(R.string.second), getResources().getColor(R.color.teal));
      adapter.add(getResources().getString(R.string.third), getResources().getColor(R.color.amber));
      viewPager.setAdapter(adapter);

      Full example you can find here: https://github.com/AlexZhukovich/TabLayoutDemoApp/blob/master/app/src/main/java/com/alexzh/tablayoutapp/MainActivity.java

Leave a comment