Parallax Scrolling Tabs with Android Design Support Library

Material Design has seen the rise in on-scroll animations in Android apps. Previously we’ve seen such examples with the Flexible Space with Image and Quick Return pattern. In this post, we’ll look at making parallax scrolling Tabs using Android Design Support Library.

Parallax scrolling has been very popular in web design and now in app development as well. I’ve seen quite a few people wanting to implement this and I wanted to provide a solution without using a third party library. So here it is.

Creating Parallax Scrolling on Android is nothing but the Flexible Space with Image pattern, with an added TabLayout.

parallax scroll header tabs

Parallax scrolling Tabs with Header

New to Android Design Support Library? Read these:

Parallax Scrolling Layout

Unlike the typical Material Design Tabs attached to the Toolbar, Tabs here are transparent. Here is the layout.

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/htab_maincontent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/htab_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/htab_collapse_toolbar"
            android:layout_width="match_parent"
            android:layout_height="256dp"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/htab_header"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/header"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/htab_toolbar"
                android:layout_width="match_parent"
                android:layout_height="104dp"
                android:gravity="top"
                android:minHeight="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:titleMarginTop="13dp" />

            <android.support.design.widget.TabLayout
                android:id="@+id/htab_tabs"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:layout_gravity="bottom"
                app:tabIndicatorColor="@android:color/white" />

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

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

    <android.support.v4.view.ViewPager
        android:id="@+id/htab_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

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

If you’ve taken my word of advice and gone through my posts linked above, you would note that I have simply added a TabLayout wrapped in a CollapsingToolbarLayout.

This positioning is important to get the parallax scrolling to work.

Layout Breakdown

Note the highlighted lines:

18. CollapsingToolbarLayout’s height denotes the height we want our header view to have

35. Toolbar height = (Toolbar Height) 56dp + (Tabs Height) 48dp = 104dp

36. & 40. To vertically adjust and center Toolbar title.

layout-parallax-scrolling-breakdown

Breakdown of layout metrics

NOTE:

Altering the Toolbar height causes its title to get misaligned. This is why I’ve opted for a manually positioning the title. More on this at StackOverflow.

Setting up ViewPager in Activity.java

In case you forgot, the Tabs need a ViewPager to work with, so let’s take care of that in our Activity.java.

public static class DummyFragment extends Fragment {
     
      public DummyFragment() {
      }

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View view = inflater.inflate(R.layout.dummy_fragment, container, false);
          ...
          RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);

          LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
          recyclerView.setLayoutManager(linearLayoutManager);

          SimpleRecyclerAdapter adapter = new SimpleRecyclerAdapter(list);
          recyclerView.setAdapter(adapter);
          ...
          return view;
      }
  }

Note that DummyFragment is just a placeholder which I’m using with a different background color for each of my Tabs. You on the other hand must define a Fragment accordingly for each of your Tabs.

Android Material UI Template 8 in 1 CodeCanyon

ViewPager Adapter

A minimal Adapter for our ViewPager. (To hold 3 Fragments)

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

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
Hooking up ViewPager with TabLayout

Finally we’ll attach the ViewPager to our TabLayout in the Activity’s onCreate() method.

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

 tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                viewPager.setCurrentItem(tab.getPosition());

                switch (tab.getPosition()) {
                    case 0:
                        showToast("One");
                        break;
                    case 1:
                        showToast("Two");
                        ...
                  }
               }

  private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new DummyFragment(getResources().getColor(R.color.accent_material_light)), "CAT");
        adapter.addFrag(new DummyFragment(getResources().getColor(R.color.ripple_material_light)), "DOG");
        adapter.addFrag(new DummyFragment(getResources().getColor(R.color.button_material_dark)), "MOUSE");
        viewPager.setAdapter(adapter);
    }
...

The setupViewPager() method simply initializes my Fragment and adds them to the ViewPager.

Nothing out of the ordinary here. The Material Design Tabs post does the same thing, which is why this has minimal explanation. However if you get stuck anywhere, below is a link to the source code (GitHub) which you can refer to 🙂

Dynamic Tab color with Palette API

The color you see the Toolbar + TabLayout take, is picked from the header image. Courtesy of the Palette API.

Using this, we’ll set colors for the Toolbar, TabLayout and Status Bar. This is easily done by the following code snippet:

Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
            @SuppressWarnings("ResourceType")
            @Override
            public void onGenerated(Palette palette) {

                int vibrantColor = palette.getVibrantColor(R.color.primary_500);
                int vibrantDarkColor = palette.getDarkVibrantColor(R.color.primary_700);
                collapsingToolbarLayout.setContentScrimColor(vibrantColor);
                collapsingToolbarLayout.setStatusBarScrimColor(vibrantDarkColor);
            }
        });

Final Output

With everything in place, run your app and scroll down and watch that beautiful parallax scrolling.

parallax scrolling header tab op

Parallax scrolling Tabs output

We have a neat TabLayout that plays nice with our Toolbar. Our header image scrolls nicely and fades into our image’s primary vibrant color.

As you can see this is a neat pattern in use which many of you would have seen. A perfect use case for this would be in apps that have categories (sub divisions) like the Play Store app, and also require a neat header image (Master Detail being the perfect example).

SOURCE CODE:
Find the source code for this project on GitHub.

Alternate Library

If you’re not satisfied with the parallax scrolling the Design Support Library provides, or desire a greater degree of control and flexibility, you can use MaterialViewPager by florent37 on GitHub.

Do share the post if you liked it!

Cheers.

App developer with an eye for design. Loves to create apps with good UI/ UX that doesn’t annoy people. In his spare time, he likes to draw and paint.

Enjoyed this article? Please spread the word.

Subscribe to Newsletter
Be the first to get latest updates and exclusive content
straight to your email inbox.
STAY UPDATED
Chill, I hate spam too. You can unsubscribe anytime.

Top Recommended Books by StackOverflow Users

Suleiman

App developer with an eye for design. Loves to create apps with good UI/ UX that doesn't annoy people. In his spare time, he likes to draw and paint.

You may also like...

Enjoyed this article? Please spread the word.

Subscribe to Newsletter
Be the first to get latest updates and exclusive content
straight to your email inbox.
STAY UPDATED
Chill, I hate spam too. You can unsubscribe anytime.

Gradle setup, ProGuard rules, Material Design palette, metrics and much more

FREE Material Design Starter Project

For more details, click on the below link.
GET IT NOW FOR ANDROID STUDIO!
Download FREE
STARTER PROJECT
Material Design Template Project for Android Studio
DOWNLOAD STARTER PROJECT
12 Tab themes, 100+ Components & more!
Save time and develop faster with this app.
  • Ready-to-use XML & Drawables
  • Pre-coded, customizable UI
  • Trusted by 2300+ devs
GET THE APP
Don't miss this App Template (12 tab themes & more) !