How to add margins between tabs in TabLayout

Tabs… Almost each and every application has at least one screen with tabs. Using that UI pattern gives us the desired high level organization of the content we have in our app.

Several months ago I had to implement a TabLayout with margins between the tabs, which at the begging seemed like a regular task. Sadly, I was wrong. I expected to be fairly easy, but there was not a straight forward way to do that. Thus, I had to spend several hours in order to figure out how to do it.

But first, let me show you the main idea!

On the picture down below you can see just a regular TabLayout. The whole width of the layout is separated equally between the three tabs and there is no margin at all between them.

Picture 1 – A Regular TabLayout

On the second picture you can see the desired result. The margins between the tabs are present.

Picture 2 – The Desired Result

At the end, I came up with the following solution:

for(int i=0; i < mTabLayout.getTabCount(); i++) {
View tab = ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i);
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
p.setMargins(0, 0, 50, 0);
view raw hosted with ❤ by GitHub

Code description:

In general, the main idea of the code snippet above is to get each tab as a View and to add margin to it. The tricky part is how to actually get the tabs one by one. If we go through the source code of the TabLayout class, we will notice that each and every time we add a new tab to the TabLayout, that tab is being included in a SlidingTabStrip. Thus, the strip is the container of all the tabs we have. The good news is that it’s pretty easy to reach the SlidingTabStip, because it’s the first child of the TabLayout. And after that we can easily add margins to the tab views in the usual way.


Feel free to share, comment & give your opinion on the topic!

And only if you really REALLY liked the article, you can buy me a cup of coffee! Otherwise, don’t do it! Donate $1

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s