Use Tab with new ToolBar (AppCompat v7-21)

With the API 21 the method setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) is deprecated.

UPDATE 01/08/2019 (Material Components Library)

Add the dependency to your build.gradle:

dependencies { implementation ‘com.google.android.material:material:1.1.0’ }

Then you can use the new TabLayout.

<androidx.constraintlayout.widget.ConstraintLayout>

     <com.google.android.material.appbar.AppBarLayout   ...>

        <androidx.appcompat.widget.Toolbar  .../>


        <com.google.android.material.tabs.TabLayout
         ...
         />

     </com.google.android.material.appbar.AppBarLayout>

     <androidx.viewpager.widget.ViewPager 
        android:id="@+id/viewpager"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.constraintlayout.widget.ConstraintLayout>

The code is simple:

TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(pager);

UPDATE 29/05/2015 (Support Library)

With the new Design Support Library now you can use the TabLayout.

Just add this dependency to your build.gradle

compile 'com.android.support:design:22.2.0'

The code is very simple:

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

To implement many of the features of material designs you should use it within a
CoordinatorLayout and a AppBarLayout.

Something like this:

 <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_height="wrap_content"
             android:layout_width="match_parent">

         <android.support.v7.widget.Toolbar
                 ...
                 app:layout_scrollFlags="scroll|enterAlways"/>

         <android.support.design.widget.TabLayout
                 ...
                 app:layout_scrollFlags="scroll|enterAlways"/>

     </android.support.design.widget.AppBarLayout>

     <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

 </android.support.design.widget.CoordinatorLayout>

OLD

You can use a different pattern. For example you can use the same example that you can see in googleio14.

It uses a SlidingTabLayout which works with a ViewPager.

Here you can find the example (it is in your sdk example)

Here you can find the Google io14 example:

Leave a Comment