修改TabLayout下劃線的寬度和文字和線的距離
阿新 • • 發佈:2019-02-03
1、寫個工具類 封裝:
import android.content.res.Resources; import android.support.design.widget.TabLayout; import android.util.TypedValue; import android.view.View; import android.widget.LinearLayout; import java.lang.reflect.Field; /** * Copyright © 2016年 AXD. All rights reserved. */ public class TabUtils { /*** @param tabs TabLayout * @param leftDip marginLeft * @param rightDip marginRight */
public static void setIndicator(TabLayout tabs, int leftDip, int rightDip, int bottomDip) {Class<?> tabLayout = tabs.getClass();Field tabStrip = null;
try {
tabStrip = tabLayout.getDeclaredField("mTabStrip"
e.printStackTrace();
return;
}
tabStrip.setAccessible(true);LinearLayout llTab = null;
try {
llTab = (LinearLayout) tabStrip.get(tabs);} catch (IllegalAccessException e) {
e.printStackTrace();
return; } int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics()); int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
int bottom = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, bottomDip, Resources.getSystem().getDisplayMetrics());
for (int i = 0; i < llTab.getChildCount(); i++) {
View child = llTab.getChildAt(i);child.setPadding(0, 0, 0, 0);LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);params.leftMargin = left;params.rightMargin = right;
params.bottomMargin = bottom;child.setLayoutParams(params);
child.invalidate();
}
}
}
2、在Activity呼叫
tab_view.post(new Runnable() { @Override public void run() { TabUtils.setIndicator(tab_view,10,10); } });