How to implement sliding tab navigation with multiple fragments

wasimsandhu picture wasimsandhu · Nov 26, 2014 · Viewed 9.8k times · Source

I want to add some proper navigation to my app. I have two fragments and I want to make a title strip tabs (similar to the one in Play Newsstand or the Play Store with material design) that switches between the two fragments. I don't have a very good understanding of the ViewPager or PagerAdapter. I'm also trying to use this library. I don't know where to get started. Thanks in advance.

Answer

wasimsandhu picture wasimsandhu · Nov 27, 2014

I actually did something myself for once. Okay.

First, add the library to your dependencies in the build.gradle file.

dependencies {
    compile 'com.jpardogo.materialtabstrip:library:1.0.6'
}

This is what my activity_main.xml looks like. I added the PagerSlidingTabStrip (with my own customization, see the Github repo for more) and my ViewPager from the support library.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame"
android:fitsSystemWindows="true" >

<include layout="@layout/toolbar" />

<com.astuetz.PagerSlidingTabStrip
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:background="#33B5E5"
    android:textColor="#FFFFFF"
    app:pstsIndicatorColor="#FFFFFF"
    app:pstsPaddingMiddle="true" />

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

Next, I did the following steps in the onCreate() method of my MainActivity.java:

    // Initialize the ViewPager and set an adapter
    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(new PagerAdapter(getSupportFragmentManager()));

    // Bind the tabs to the ViewPager
    PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    tabs.setViewPager(pager);

And finally, the FragmentPagerAdapter class, also in MainActivity.java. Notice the Fragment getItem() method; this is where I switched between my fragments using the position of the tabs.

class PagerAdapter extends FragmentPagerAdapter {

private final String[] TITLES = {"Regular Tenses", "Perfect Tenses"};

public PagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public CharSequence getPageTitle(int position) {
    return TITLES[position];
}

@Override
public int getCount() {
    return TITLES.length;
}

@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            return new MainFragment();
        case 1:
            return new PerfectFragment();
    }

    return null;
   }
}