TabLayout更改下划线长度和内容保持一致
程序员文章站
2022-06-01 07:50:17
...
先上效果图
主要是通过反射强制修改每个子Tab的左右边距,代码很简单,一看就明了
下面献上代码
public void setTabLine(TabLayout tab,int left,int right){
try {
Class<?> tablayout = tab.getClass();
Field tabStrip = tablayout.getDeclaredField("mTabStrip");
tabStrip.setAccessible(true);
LinearLayout ll_tab= (LinearLayout) tabStrip.get(tabLayout);
for (int i = 0; i < ll_tab.getChildCount(); i++) {
View child = ll_tab.getChildAt(i);
child.setPadding(0,0,0,0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT,1);
//修改两个tab的间距
params.setMarginStart(BasicUtils.dip2px(context,left));
params.setMarginEnd(BasicUtils.dip2px(context,right));
child.setLayoutParams(params);
child.invalidate();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
Log.e(TAG,e.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
Log.e(TAG,e.toString());
}
}
注意1:Tablayout的Mode必须得设置为fixed,否则会滑动
示例:app:tabMode=”fixed”
注意2:Tablayout的宽不能写死,得设置为包裹内容