Android Tablayout With Fragments, ViewPager And Material Design

Whatsapp is using Android tablayout for basic navigation.

In today’s Android tablayout example, we will develop that kind of structure programmatically.

Android tablayout uses fragments, material design and view pager as basic components.

If you wish to make custom tab layout then read how to make custom tablayout in android.

Also learn how to create tab layout with different action bar for every fragment like whatsapp.

First, watch the output, then we will prepare it.

Download Source Code for Android tablayout example

[sociallocker] Download SimpleTabsDemonuts [/sociallocker]

Step 1: Create a new project in Android Studio.

Always try to create new project in android studio with empty activity.

Step 2: Update build.gradle(Module:app) file

Add below in build.gradle(Module:app) file

Whole source code for build.gradle(Module:app)

Step 3: Updating colors.xml

Go to the res->values->colors.xml directory

update colors.xml as below

Step 4: Preparing three fragments

Create three fragments and give them name as “OneFragment,” “TwoFragment,” and “ThreeFragment.

In every application with tab layout, use of fragment is must. Gmail is also using same concept.

Fragments simplifies the back stack problem arises if we use activity instead of fragment.

Here, we are using three fragments. You can increase or decrease this number as per your requirements.

Add below code in fragment_one.xml

Add following in OneFragment.java

Copy below source code in fragment_two.xml

Copy following code in TwoFragment.java

Add below code in fragment_three.xml

Paste below code in ThreeFragment.java

Step 5: Updating MainActivity

update activity_main.xml as below

Update MainActivity.java as per following

Step 6: Explanation of MainActivity.java

First of all setupViewPager() method is called.

Consider below source code

In above method, we have added each fragment to view pager adapter.

addFragment() method have two parameters. First have the object of fragments and second have the name of that fragment.

The value of Second parameter will shown as the name of the tab.

After that, ViewPagerAdapter class is defined. You do not need to do any modification in this class.

Kotlin Version

Kotlin version of this tutorial : TabLayout  Android Kotlin

That is all for Android tablayout example.

Comment if you have queries or a review. Thank you.

Hardik Parsania

I am mobile app developer. I am always passionate about solving complex and real world problems.I have developed many apps with great interest and superior logical skills.

You may also like...

Leave a Reply

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