Well, I actually found a proper solution for that. Forget about PagerTabStrip
;)
Apparently, Google released a sample app that features the exact source code they used in Google Play app. It's super easy to use. Download the sample app and copy two files from there: SlidingTabLayout.java
and SlidingTabStrip.java
.
Then in your layout XML, add the following above the ViewPager
(change com.example
to your package name):
<com.example.SlidingTabLayout
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_marginTop="5dp"
android:layout_weight="1.5"
android:layout_width="match_parent"
android:background="@android:color/white"
android:layout_height="0dp"/>
And add the following to the activity after you initialize the ViewPager
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(new GridPagerAdapter(getSupportFragmentManager()));
// Initialize the SlidingTabLayout. Note that the order is important. First init ViewPager and Adapter and only then init SlidingTabLayout
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
SlidingTabLayout
's API allows you to easily do basic styling such as, changing the tab color, the divider color, the indicator color, etc.
One more important thing, the SlidingTabLayout
that Google provided works well when you have many tabs. But, if you have, for example, three tabs, you'll see that all the tabs are aligned to the left and there's a big gap between the last tab and the width of the view.
To overcome this, modify SlidingTabLayout.java
after line 173 just below TextView textView = new TextView(context);
add the following line:
textView.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
Now the space among the tabs will be divided correctly: