使用TabLayout,但是 tabMode="scrollable"
时,两个tab之间的间距太开了,实在不美观,看TabLayout
源码,原来是设置了最小间距导致的:
this.scrollableTabMinWidth = res.getDimensionPixelSize(dimen.design_tab_scrollable_min_width);
<dimen name="design_tab_scrollable_min_width">72dp</dimen>
ui工程师要求是47dp,于是通过反射的方法改变这个值就可以了:
public class MyTabLayout extends TabLayout {
// 一屏显示多少个tab
private static final int TabViewNumber = 8;
// support 低版本可能不一样
private static final String SCROLLABLE_TAB_MIN_WIDTH = "scrollableTabMinWidth";
public MyTabLayout(Context context) {
super(context);
initTabMinWidth();
}
public MyTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initTabMinWidth();
}
public MyTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initTabMinWidth();
}
private void initTabMinWidth() {
// int screenWidth = getResources().getDisplayMetrics().widthPixels;
// int tabMinWidth = screenWidth / TabViewNumber;
// scrollable模式时,tab的最小宽度
int tabMinWidth = (int) getResources().getDimension(R.dimen.dp_47);
Field field;
try {
field = TabLayout.class.getDeclaredField(SCROLLABLE_TAB_MIN_WIDTH);
field.setAccessible(true);
field.set(this, tabMinWidth);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
注意:
com.android.support:design:28.0.0
,低版本字段名可能不一样## 不混淆 TabLayout
-keepclasseswithmembernames class android.support.design.widget.TabLayout {
*;
}
参考资料:https://blog.csdn.net/wanglaohushiwo/article/details/72857691