Todor Kostov Todor Kostov - 1 year ago 183
Android Question

How to add margin between tabs in TabLayout?

Is there a way to add margin between the tabs in a TabLayout? I've tried with using a custom style for Widget.Design.TabLayout, but there are properties only related to padding, but no margins.

Answer Source

Ok mates, after spending 2-3 hours on that I finally found a solution.

If you are using TabLayout there is no way to add margins to the tabs by using styles and so on. (as @Connecting life with Android earlier)

But, you can do that by writing some Java code. All in all your code should look similar to that one:

            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);

In order to get each and every tab as a View we have to first get the container which contains them. In this case the TabLayout is using a SlidingTabStrip as a container for the tabs. The SlidingTabStrip is the first child of the TabLayout:

View tab = ((ViewGroup) mTabLayout.getChildAt(0))

And after this small detail, everything is pretty straight forward.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download