Create a simple ViewPager Tabs in Android

ViewPager Tabs
In this tutorial focussed on beginners we will see how to create a VIewPager with Tabs in Android. The ViewPager Tabs setup is pretty simple and discussed below. The Sample Source Code is available at the end of this article.
ViewPager
According to the official documentation, ViewPager is most often used in conjunction with Fragment, which is a convenient way to supply and manage the lifecycle of each page. There are standard adapters implemented for using fragments with the ViewPager, which cover the most common use cases. These are FragmentPagerAdapter and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.
Pager Adapters
As described earlier, We have two standard ViewPager Adapters,
- FragmentPagerAdapter is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state.
- FragmentStatePagerAdapter is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.
In simple words, If your ViewPager is having few fixed number of Tabs say 3 or 4, use FragmentPagerAdapter. If it has more Tabs or endless number of Tabs, use FragmentStatePagerAdapter.
In this example we will see how to create a Simple ViewPager Tabs setup with three Fixed Tabs using FragmentPagerAdapter.
Tabs
For Tabs, we will be using fixed TabLayout.
Now lets move on to the coding part.
Gradle Dependencies
Add the below dependencies in your build.gradle file and sync the project.
1 2 3 4 5 6 7 8 9 10 |
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) // ignore if you have already added compile 'com.android.support:appcompat-v7:24.2.1' compile 'com.android.support:design:24.2.1' } |
Layouts
Create the following layouts.
activity_main.xml – This is our main layout containing ViewPager and TabLayout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?xml version="1.0" encoding="utf-8"?> <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/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.gadgetsaint.viewpagerexample.MainActivity"> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="fixed" android:background="?attr/colorPrimary" android:minHeight="?attr/actionBarSize" app:tabGravity="fill" app:tabTextColor="#FFF" app:tabSelectedTextColor="@color/colorAccent" /> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> |
Note that app:tabMode=”fixed” and app:tabGravity=”fill” Since we are using fixed Tabs which fills the entire width.
To change the text color or selected text color of Tabs modify tabTextColor and tabSelectedTextColor respectively.
fragment_one.xml – Layout for Fragment attached to First tab
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="#D81B60" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fragment One" android:textSize="40dp" android:textStyle="bold" android:textColor="#fff" android:layout_centerInParent="true"/> </RelativeLayout> |
Similarly create two more layout fragment_two.xml and fragment_three.xml for Fragment attached to second and third Tabs respectively. In case of doubts check the sample source code at the end of this article.
Now since all the layouts are created lets create the Fragment classes.
Fragments
Create three Fragments – FragmentOne, FragmentTwo, FragmentThree similar to the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
ublic class FragmentOne extends Fragment { public FragmentOne() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_one, container, false); } } |
Don’t forget to change the layouts in each Fragment with the corresponding one.
Now lets create the MainActivity class where we add an adapter to the ViewPager and link it with TabLayout
MainActivity.java
Paste the below code in your MainActivity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager viewPager = (ViewPager) findViewById(R.id.pager); ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); // Add Fragments to adapter one by one adapter.addFragment(new FragmentOne(), "FRAG1"); adapter.addFragment(new FragmentTwo(), "FRAG2"); adapter.addFragment(new FragmentThree(), "FRAG3"); viewPager.setAdapter(adapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } // Adapter for the viewpager using FragmentPagerAdapter class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = 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 addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } } |
In the above class we have created an adapter which is set to the ViewPager. Run the code and check the output.
Preview
SourceCode
Please download the source code from Github
Let me know your Suggestions / Queries in comments.
Follow GadgetSaint on Facebook / Twitter for updates.
Excellent Tutorial, well explained. Thank you.
Welcome 🙂
Can this program also be used for creating tab inside fragment?
Please i need a code to create tablayout inside a fragment in Navigation drawer?
No mess, no fuss introduction. Perfect for first time implementation. Thank you.
Superb Tutorial! Thank you very much
thank you! very simple and effective! yo are the perfect teacher!
Thanks for the tutorial!
I am struggling to know where I should start for the following: How would you go about modifying this code in order to have each tab display a different end point?
The short one and simple one… I have been working since a day… All irrelative info i got. This is the perfect, short, simple.. Thanking you so much
Why use Fragments at all? Why not create Views.
I see you don’t monetize your site, don’t waste your traffic,
you can earn extra cash every month because you’ve got hi quality content.
If you want to know how to make extra bucks, search for: Ercannou’s essential adsense alternative
I often visit your blog and have noticed that you don’t update it
often. More frequent updates will give your website higher rank & authority in google.
I know that writing content takes a lot of time, but you can always help yourself with miftolo’s tools which will shorten the
time of creating an article to a couple of seconds.
I can scroll between tabs but it doesn’t show the tabs at the top, help??
Special tnx man! 😉
Thanks dude..
Its clear simple and easy to understand.