How to create Toolbar Tabs with ViewPager in material design

18,706

Solution 1

Anyone know anything about how tabs are done in API 21/AppCompat Toolbar?

There are no Toolbar tabs. The pattern of having tabs in the action bar was deprecated by Material Design, and when they created Toolbar, they dropped tabs.

So can anyone give examples or articles about how to make toolbar tabs with viewpager.

There are no Toolbar tabs.

You are welcome to use PagerTabStrip, the TabPageIndicator from the ViewPagerIndicator library, PagerSlidingTabStrip, etc. for your ViewPager tabs.

Solution 2

1 . Copy SlidingTabLayout.java from https://developer.android.com/samples/SlidingTabsColors/src/com.example.android.common/view/SlidingTabLayout.html and paste it in your package.

MainActivity.java

public class MainActivity extends ActionBarActivity {

static final String LOG_TAG = "SlidingTabsBasicFragment";
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_sample);
    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);

    mViewPager = (ViewPager) findViewById(R.id.viewpager);
    mViewPager.setAdapter(new SamplePagerAdapter());
    mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
    mSlidingTabLayout.setViewPager(mViewPager);

    /*
     * FragmentTransaction transaction =
     * getSupportFragmentManager().beginTransaction();
     * SlidingTabsBasicFragment fragment = new SlidingTabsBasicFragment();
     * transaction.replace(R.id.sample_content_fragment, fragment);
     * transaction.commit();
     */

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

class SamplePagerAdapter extends PagerAdapter {

    /**
     * @return the number of pages to display
     */
    @Override
    public int getCount() {
        return 5;
    }

    /**
     * @return true if the value returned from
     *         {@link #instantiateItem(ViewGroup, int)} is the same object
     *         as the {@link View} added to the {@link ViewPager}.
     */
    @Override
    public boolean isViewFromObject(View view, Object o) {
        return o == view;
    }

    // BEGIN_INCLUDE (pageradapter_getpagetitle)
    /**
     * Return the title of the item at {@code position}. This is important
     * as what this method returns is what is displayed in the
     * {@link SlidingTabLayout}.
     * <p>
     * Here we construct one using the position value, but for real
     * application the title should refer to the item's contents.
     */
    @Override
    public CharSequence getPageTitle(int position) {
        return "Item " + (position + 1);
    }

    // END_INCLUDE (pageradapter_getpagetitle)

    /**
     * Instantiate the {@link View} which should be displayed at
     * {@code position}. Here we inflate a layout from the apps resources
     * and then change the text view to signify the position.
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // Inflate a new layout from our resources

        View view = getLayoutInflater().inflate(R.layout.pager_item,
                container, false);
        // Add the newly created View to the ViewPager
        container.addView(view);

        // Retrieve a TextView from the inflated View, and update it's text
        TextView title = (TextView) view.findViewById(R.id.item_title);
        title.setText(String.valueOf(position + 1));

        Log.i(LOG_TAG, "instantiateItem() [position: " + position + "]");

        // Return the View
        return view;
    }

    /**
     * Destroy the item from the {@link ViewPager}. In our case this is
     * simply removing the {@link View}.
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        Log.i(LOG_TAG, "destroyItem() [position: " + position + "]");
    }

}

}

fragment_sample.xml

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

    <android.support.v7.widget.Toolbar
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/my_awesome_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:minHeight="?attr/actionBarSize"

        app:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <com.example.android.common.view.SlidingTabLayout
                android:id="@+id/sliding_tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </android.support.v7.widget.Toolbar>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white" />

</LinearLayout>

Pager_item.xml

<?xml version="1.0" encoding="utf-8"?>

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

    <TextView
          android:id="@+id/item_subtitle"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textAppearance="?android:attr/textAppearanceLarge"
          android:text="Page:"/>

    <TextView
          android:id="@+id/item_title"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textSize="80sp" />

</LinearLayout>
Share:
18,706
Nurzhan Nogerbek
Author by

Nurzhan Nogerbek

✌️ Hello, friend! I am glad to see you on my personal StackOverflow profile. My name is 𝗡𝘂𝗿𝘇𝗵𝗮𝗻. 🏠 I am living in 𝗔𝗹𝗺𝗮𝘁𝘆 🍎 and I am from 𝗞𝗮𝘇𝗮𝗸𝗵𝘀𝘁𝗮𝗻 🇰🇿. 👦🏻 Since I first wrote my first piece of code in 𝗧𝘂𝗿𝗯𝗼 𝗣𝗮𝘀𝗰𝗮𝗹 as a child using my father's personal computer in 𝗪𝗶𝗻𝗱𝗼𝘄𝘀 𝟵𝟱, software development has become my passion. ⏱ I still live with this passion in the commercial software development industry, where I have been working for 𝟱+ years. 🏢 I started my career from developing multi-user web applications for the outsourcing company 𝗥𝘂𝗯𝗶𝘂𝘀 in 2015. 🏦 Then I worked for 1.5 years in the 𝗞𝗮𝘇𝗮𝗸𝘀𝘁𝗮𝗻 𝗦𝘁𝗼𝗰𝗸 𝗘𝘅𝗰𝗵𝗮𝗻𝗴𝗲 in FinTech projects. During this short time, I managed to develop 𝟰 financial and analytical web projects for the company. 📡 I worked for the largest telecommunications company in Central Asia from 2018 to 2020. I am proud to have participated in the creation of 𝟳 scalable distributed Big Data systems in a microservice architecture at 𝗩𝗘𝗢𝗡 company. 🚀 Since the fall of 2020, I have been involved in the development of a fast-growing and promising startup at 𝗦𝗺𝗮𝗿𝘁𝗟𝗮𝗯 company. 🛠 I usually use 𝗚𝗼𝗹𝗮𝗻𝗴 for 𝗕𝗮𝗰𝗸𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗺𝗲𝗻𝘁, 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 for 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗺𝗲𝗻𝘁, 𝗦𝗰𝗮𝗹𝗮 for 𝗗𝗮𝘁𝗮 𝗘𝗻𝗴𝗶𝗻𝗲𝗲𝗿𝗶𝗻𝗴, and 𝗣𝘆𝘁𝗵𝗼𝗻 for 𝗗𝗮𝘁𝗮 𝗦𝗰𝗶𝗲𝗻𝗰𝗲. 📚 I have a 𝗠𝗮𝘀𝘁𝗲𝗿'𝘀 𝗗𝗲𝗴𝗿𝗲𝗲 in 𝗖𝗼𝗺𝗽𝘂𝘁𝗲𝗿 𝗦𝗰𝗶𝗲𝗻𝗰𝗲 from 𝗧𝗼𝗺𝘀𝗸 𝗣𝗼𝗹𝘆𝘁𝗲𝗰𝗵𝗻𝗶𝗰 𝗨𝗻𝗶𝘃𝗲𝗿𝘀𝗶𝘁𝘆 in Russia. 🤖 I have implemented 𝟭𝟱+ successful web projects that have made life easier for thousands of users. You can easily find details of these projects in my GitHub profile. 📩 Feel free to contact me with your ideas and suggestions!

Updated on June 09, 2022

Comments

  • Nurzhan Nogerbek
    Nurzhan Nogerbek almost 2 years

    Anyone know anything about how tabs are done in API 21/AppCompat Toolbar?

    A lot of materials and articles what I found were old. They used old methods with ActionBar which don`t work now. At this moment I just created toolbar and have no ideas about toolbar tabs. So can anyone give examples or articles about how to make toolbar tabs with viewpager?

  • Nurzhan Nogerbek
    Nurzhan Nogerbek over 9 years
    Thanks for your answer. I just make my first steps in android programming. I've tried SlidingTabs and some other libraries, but they all are outdated. They used old methods with ActionBar. As you know now with Android 5.0, the whole ActionBar is being replaced by ToolBar. Are you sure that this your library will be work?!
  • Nurzhan Nogerbek
    Nurzhan Nogerbek over 9 years
    Do you have any examples or articles about tabs in material design?!
  • CommonsWare
    CommonsWare over 9 years
    @NurzhanNogerbek: "As you know now with Android 5.0, the whole ActionBar is being replaced by ToolBar" -- not really. Using a Toolbar as your action bar is an option. It is not required. You can still use ActionBar the way you have previously, though tab and list navigation are deprecated. "Are you sure that this your library will be work?" -- since none of the options I cited have anything to do with the action bar, I feel quite confident that they work. "Do you have any examples or articles about tabs in material design?" -- google.com/design/spec/components/tabs.html
  • Nurzhan Nogerbek
    Nurzhan Nogerbek over 9 years
    Thanks for this code! I have mistake in SamplePagerAdapter.java document which you give me in this place getLayoutInflater(). How solve this problem?
  • kunal.c
    kunal.c over 9 years
    Please elaborate your problem
  • Nurzhan Nogerbek
    Nurzhan Nogerbek over 9 years
    I pasted SlidingTabStrip and SlidingTabLayout in my project as you said, then i used your code in my Main Activity, then i created SamplePagerAdapter.java document and used your code but i have one mistake in it. getLayoutInflater() Cannot resolve method. So where this method discribed and what we need to do in this method! Pls i need your view to this problem!
  • Apurva
    Apurva over 8 years
    maybe you missed tabLayout
  • CommonsWare
    CommonsWare over 8 years
    @Apurva: TabLayout has nothing to do with Toolbar. For example, this sample project shows a TabLayout in a project with no Toolbar.
  • carl
    carl almost 5 years
    So this means that in the new toolbar design, we are forced to use two lines at least, always, one for toolbar and one for tabs? SO IDIOTIC on a small screen (dependant on your features on the toolbar).