设置tablayout下划线的宽度 (TabLayout和28之前有差异,mTabStrip已经是slidingTabIndicator了,API 28下TabLayout的差异)
两种实现方式
public static void reflex(final TabLayout tabLayout){
tabLayout.post(new Runnable() {
@Override
public void run() {
try {
LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);
int dp10 = dp2px(50);
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
View tabView = mTabStrip.getChildAt(i);
Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
mTextViewField.setAccessible(true);
TextView mTextView = (TextView) mTextViewField.get(tabView);
tabView.setPadding(0, 0, 0, 0);
int width = 0;
width = mTextView.getWidth();
if (width == 0) {
mTextView.measure(0, 0);
width = mTextView.getMeasuredWidth();
}
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
params.width = width ;
params.leftMargin = dp10;
params.rightMargin = dp10;
tabView.setLayoutParams(params);
tabView.invalidate();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
}
public static void setIndicatorWidth(@NonNull final TabLayout tabLayout, final int margin) {
tabLayout.post(new Runnable() {
@Override public void run() {
try {
Field slidingTabIndicatorField = tabLayout.getClass().getDeclaredField("slidingTabIndicator");
slidingTabIndicatorField.setAccessible(true);
LinearLayout mTabStrip = (LinearLayout) slidingTabIndicatorField.get(tabLayout);
for (int i = 0; i < mTabStrip.getChildCount(); i++) { View tabView = mTabStrip.getChildAt(i);
Field textViewField = tabView.getClass().getDeclaredField("textView");
textViewField.setAccessible(true);
TextView mTextView = (TextView) textViewField.get(tabView);
tabView.setPadding(0, 0, 0, 0);
int width = mTextView.getWidth();
if (width == 0) { mTextView.measure(0, 0);
width = mTextView.getMeasuredWidth();
}
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
params.width = width; params.leftMargin = margin; params.rightMargin = margin;
tabView.setLayoutParams(params); tabView.invalidate();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
}
原简书博文,现迁至这