Leandro Hoffmann Leandro Hoffmann - 4 months ago 13
Android Question

Use Tab with new ToolBar (AppCompat v7-21)

I was using Support ActionBar with tabs and using custom ActionBar theme (created with http://jgilfelt.github.io/android-actionbarstylegenerator/), showing the tabs only when the user expand the search view.

public boolean onMenuItemActionExpand(MenuItem item) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
return true;
}
}


I migrated from ActionBar to ToolBar. My app really needs to support api 9.

Is there a way to use this?:

Toolbar toolbar = (Toolbar) findViewById(R.id.new_actionbar);
setSupportActionBar(toolbar);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);


If is possible, how to use my custom theme or style the toolbar?

Documentation say that is deprecated and suggests to use other type of navigation.
But I don't know other component in android to have the same functionality.

Some help?

Answer

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

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:

UPDATE 29/05/2015

With the new Design Support Library now you can use the new 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>

You can find more info in the Stackoverflow Documentation.