How to add margin between tabs in TabLayout?

Is there any way to add margin between tabs in TabLayout? I tried using a custom style for Widget.Design.TabLayout , but there are properties related only to filling, but without fields.

+9
android android-tablayout
Apr 11 '16 at 12:35
source share
3 answers

Well, after 2-3 hours of work, I finally found a solution.

If you use TabLayout, there is no way to add fields to tabs using styles, etc. (like @Connecting life with Android earlier)

But you can do this by writing Java code. In general, your code should look something like this:

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); tab.requestLayout(); } 

To get each tab as a view, we must first get the container that contains them. In this case, TabLayout uses SlidingTabStrip as a container for tabs. SlidingTabStrip is the first child of TabLayout:

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

And after this small detail, everything is pretty straightforward.

+22
Apr 11 '16 at 15:00
source share

@ Todor Kostov answered well, but the center of the tabs eludes because the last tab also has a margin.

so use mTabLayout.getTabCount() - 1 instead of mTabLayout.getCodeCount() .

  for(int i=0; i < mTabLayout.getTabCount() - 1; i++) { View tab = ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i); ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) tab.getLayoutParams(); p.setMargins(0, 0, 50, 0); tab.requestLayout(); } 
+1
Jun 29 '17 at 6:38
source share

This is how the field is set for four different tabs. You can change the values โ€‹โ€‹of the setMargins functions (v1, v2, v3, v4) to get a suitable setting for the number of tabs you work with. Hope this helps. Note that tabHost is a TabHost object that hosts the different tabs that you work with.

 Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); View currentView; for(int i=0;i<tabHost.getTabWidget().getChildCount();i++) { //This code removes divider between tabs tabHost.getTabWidget().setDividerDrawable(null); tabHost.getTabWidget().getChildAt(i).setLayoutParams(new LinearLayout.LayoutParams((width/8)-2,50)); currentView = tabHost.getTabWidget().getChildAt(i); LinearLayout.LayoutParams currentLayout = (LinearLayout.LayoutParams) currentView.getLayoutParams(); currentLayout.setMargins(30, 5, 80, 0); } 
0
Nov 21 '16 at 23:07
source share



All Articles