TabLayout 设置指示器宽度问题
作者:互联网
public static void setTabLayoutWidth(int left, int right, TabLayout tabLayout, Activity Activity) {
try {
Field slidingTabIndicatorField;
Field textViewField;
// 拿到tabLayout的slidingTabIndicator属性
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
slidingTabIndicatorField = tabLayout.getClass().getDeclaredField("slidingTabIndicator");
} else {
slidingTabIndicatorField = tabLayout.getClass().getDeclaredField("mTabStrip");
}
slidingTabIndicatorField.setAccessible(true);
LinearLayout mTabStrip = (LinearLayout) slidingTabIndicatorField.get(tabLayout);
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
View tabView = mTabStrip.getChildAt(i);
//拿到tabView的mTextView属性
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
textViewField = tabView.getClass().getDeclaredField("textView");
} else {
textViewField = tabLayout.getClass().getDeclaredField("mTextView");
}
textViewField.setAccessible(true);
TextView mTextView = (TextView) textViewField.get(tabView);
tabView.setPadding(0, 0, 0, 0);
// 因为想要的效果是字多宽线就多宽,所以测量mTextView的宽度
int width = mTextView.getWidth();
if (width == 0) {
mTextView.measure(0, 0);
width = mTextView.getMeasuredWidth();
}
// 设置tab左右间距,注意这里不能使用Padding,因为源码中线的宽度是根据tabView的宽度来设置的
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
params.width = width;
params.leftMargin = left;
params.rightMargin = right;
tabView.setLayoutParams(params);
tabView.invalidate();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
app:tabIndicatorFullWidth="false"设置为false 就是指示线跟tabitem的文字一样宽
要设置为true 才能设置上边的才有效
有同学肯定好奇为啥上边还有版本判断
因为sdk大于等于28 是 slidingTabIndicator这个 小于的就是 mTabStrip 因为sdk版本都有差异 找不到的话 就会 Exception
然后就尴尬了
这是根据我日常遇到的问题分享出来 希望能解决各位同学的问题 不许勿喷!白白
标签:mTextView,指示器,tabView,width,宽度,params,TabLayout,tabLayout,textViewField 来源: https://blog.csdn.net/wan903531306/article/details/105792715