在使用TabLayout的时候,往往需要改变下标的宽高,高度比较好设置,直接设置属性 :
app:tabIndicatorHeight="1.5dp"
但是宽度在不自定义tab的情况下似乎并没有直接提供相关的属性,经过查阅自己写个方法设置才能实现效果,代码如下:
public void setIndicator(TabLayout tabs, int leftDip, int rightDip) { Class<?> tabLayout = tabs.getClass(); Field tabStrip = null; try { tabStrip = tabLayout.getDeclaredField("mTabStrip"); } catch (NoSuchFieldException e) { e.printStackTrace(); } tabStrip.setAccessible(true); LinearLayout llTab = null; try { llTab = (LinearLayout) tabStrip.get(tabs); } catch (IllegalAccessException e) { e.printStackTrace(); } 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()); 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; child.setLayoutParams(params); child.invalidate(); } }
然后调用这个方法改变下标的宽度:
//改变下标宽度 mTabLayout.post(new Runnable() { @Override public void run() { setIndicator(mTabLayout,30,30); } });
另:改变tablayout上字体的大小需要在styles.xml里设置
<style name="CustomTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textSize">14sp</item>
<item name="android:textAllCaps">false</item>
</style>
然后在xml里引用:
app:tabTextAppearance="@style/CustomTabLayoutTextAppearance"
浙公网安备 33010602011771号