Android TabLayout + Fragment Tutorial

Android TabLayout allow you navigate to another screen without open a new activity. It is always visible to the user unlike NavigationDrawer are always hidden.  The benefit of tab in android is providing the ease of navigation to another section by just clicking the tab. You also can implement add viewPager to the tablayout so it just need swipe right or left for navigate to different tab. In this tutorial, I will teach u how to create the tablayout in android. The viewPager and Fragment are include to the tablayout. So, you just need to follow my steps so you can get it done.

Android TabLayout Demo

Creating a New Project

1. Open Android Studio IDE in your computer.
2. Create a new project and Edit the Application name to “TabExample”.
(Optional) You can edit the company domain or select the suitable location for current project tutorial. Then click next button to proceed.
3. Select Minimum SDK (API 15:Android 4.0.3 (IceCreamSandwich). I choose the API 15 because many android devices currently are support more than API 15. Click Next button.
4. Choose “Tabbed Acitivity” and Click Next button
5. Lastly, press finish button.

Edit activity_main.xml layout

After create the Tabbed Activity, go to activity_main.xml and insert the following code.

Edit fragment_main.xml layout

After that, go to your fragment_main and add the textview in your layout.

Move class to dedicated file

Go to your in your package folder. Inside your code may have PlaceholderFragment and SectionsPagerAdapter class. Move those class to dedicated file which are following.

Create a new Fragment

Add a second fragment in your activity. Right click package name > New > Fragment > Fragment. I name my fragment as AnotherFragment.

Edit fragment_another.xml

In your fragment_another.xml add the textview to specific which fragment is currently open.

Edit class

Besides that, go to your and insert the following code.

Edit class

Last, go to your and paste the following code. This will add 2 fragment in the activity.

Run your Project

Now, you can start your project in your emulator. The tablayout is just easy to use and implement by yourself.

(Android TabLayout)

Source Code

(Visited 1,263 times, 1 visits today)

Yong Loon Ng

Ng Yong Loon, better known as Kristofer is a software engineer and computer scientist who doubles up as an entrepreneur.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *