Maybe you already know about ViewPager and are using something like ViewPagerIndicator by JakeWharton for indicating the title. Did you know that there is something doing that in the support library? If you use it, it looks like this:
Now how do you use this? First you need to set up your ViewPager. If you already know how to do that, please skip this part.
Setting up ViewPager
ViewPager is the Component that allows us swiping through Pages to the left and right. The best way to use a ViewPager is with Fragments. (If you do not know about Fragments yet, search for it on Google and read a little bit about it.)
To implement the ViewPager we need to do three things:
Let us look at the code to add the ViewPager to the layout:
So we use the ViewPager from the support library (make sure you have the support library in your libs folder or in the pom.xml if you use Maven).
Next we have to get the ViewPager, implement the Adapter and the Fragment. Here I implemented it in MainActivity.java:
As well we need the following xml which is used for the PageFragment:
There is some explanation needed here.
Now we the whole PagerAdapter should be working correctly. But how to get the nice headers? Continue reading.
Setting up PagerTabStrip
So you see we added the PagerTabStrip inside the ViewPager. You can play around with the colors if you like. If you just do this you will see the header, but no text. Because we did not tell the ViewPager yet what the titles are for each page. To do this we need to override getPageTitle(int position):
Once we implemented this we should see the titles correctly.
How to use with ActionBarSherlock or Maven
Problem with ActionBarSherlock and Maven is that there is only the old support library used/available. So using ActionBarSherlock for example we will not be able to find PagerTabStrip. You could just use PagerTitleStrip, but that might not be good enough for you. So what can you do? You can copy paste the code from PagerTitleStrip to your own source code. To do this without getting errors, do the following:
In the xml and java files use the same code as above, but with the PagerTabStrip2 instead of PagerTabStrip.