用反射實現(xiàn)
- 直接上代碼(可直接復(fù)制使用)
/**
* tabLayout下劃線寬度
* @param padding 左右外邊距
*/
public static void reflex(final TabLayout tabLayout, final @DimenRes int padding) {
tabLayout.post(new Runnable() {
@Override
public void run() {
try {
//拿到tabLayout的mTabStrip屬性
Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
mTabStripField.setAccessible(true);
LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);
int dp10 = tabLayout.getContext().getResources().getDimensionPixelOffset(padding);
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
View tabView = mTabStrip.getChildAt(i);
//拿到tabView的mTextView屬性
Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
mTextViewField.setAccessible(true);
TextView mTextView = (TextView) mTextViewField.get(tabView);
tabView.setPadding(0, 0, 0, 0);
//因為我想要的效果是 字多寬線就多寬,所以測量mTextView的寬度
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();
}
}
});
}
在debug包中可顯示效果,release包中無效
解決方法:
在混淆文檔proguard-rules.pro中去掉對widget包的混淆,即加上
-keep class android.support.design.widget.** { *; }**