Tab layout — How to create clickable tabs. (TabLayout and viewpager)

Gunjan Kalita
ProAndroidDev
Published in
2 min readApr 30, 2020

--

If your application is using fragments; highly probable that you will use tablayout and viewpager combo. But hey! we want things different and we will always keep wanting that. Hence, introducing to you — — Android tablayout with buttons in tabs.

To achieve it; is actually really simple. But it can be a little lenghty. So, please bear with me. To break down the process, we will first create a layout for the tabs. After that, we will inflate the layout in the tabs and then we will simply add the click listners to switch between different fragments.

Let us start with the layout for tabs. It simply contains two image buttons with left and right arrow icons and a text view to show a name on the tab. We will add a click listner in the image buttons to navigate through the fragments. Refer the code bellow to know more about the layout.

In the activity file after setting up the basic viewpager and tablayout combination, we will add java code to manipulate the click events in the tabs and visibility of the unselected tabs.

We will now add the custom layout to each and every tab in the tab layout using java. Refer the code bellow.

Then we will create two functions, HighlightTab and FadeTab with its obvious use. The first one will highlight the selected tab with the background shown and add the click listners to the imageviews at both end. The other one will remove the the imageviews from tab and replace the background of the tab to nothing.

The last step now, to add a listner to tablayout. TabLayouts in android comes with a listner called addOnTabSelectedListener which gives us call back method to determine selected , unselected and reselected tabs in the tablayout. These methods will provide you the respective tab. In those methods; we will simply call the HighlightTab methods in the tab selected callback methods. And the FadeTab in the unselected callback method. Refer code bellow.

That is it. Now we have a tab layout that has buttons to click and a feature to switch fragments.

Have any doubts?? Shoot them right way.

Source code

--

--

Javascript | React | Node | MongoDB | MySQL. SDE 2 at Swiggy | DM for a free CV review