先看第一种方法如果这种方法好,下面的方法就不用看了,下面是Git网址
https://github.com/H07000223/FlycoTabLayout/blob/master/README_CN.md
由于最近项目需要,需要设置tabLayout下方下划线的长度.笔者上网找了半天,也没有找到方法.后来了解到在源码中对tabLayout的下划线进行了设置.并没有方法可以直接设置.
然后,笔者看到了某位大神的代码,利用反射修改下划线的宽度.先上代码:
- public void setIndicator (TabLayout tabs,int leftDip,int rightDip){
- Class<?> tabLayout = tabs.getClass();
- Field tabStrip = null;
- try {
- tabStrip = tabLayout.getDeclaredField(“mTabStrip”);
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- }
- tabStrip.setAccessible(true);
- LinearLayout llTab = null;
- try {
- llTab = (LinearLayout) tabStrip.get(tabs);
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
- int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
- for (int i = 0; i < llTab.getChildCount(); i++) {
- View child = llTab.getChildAt(i);
- child.setPadding(0, 0, 0, 0);
- LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
- params.leftMargin = left;
- params.rightMargin = right;
- child.setLayoutParams(params);
- child.invalidate();
- }
public void setIndicator (TabLayout tabs,int leftDip,int rightDip){
Class<?> tabLayout = tabs.getClass();
Field tabStrip = null;
try {
tabStrip = tabLayout.getDeclaredField("mTabStrip");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
tabStrip.setAccessible(true);
LinearLayout llTab = null;
try {
llTab = (LinearLayout) tabStrip.get(tabs);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
for (int i = 0; i < llTab.getChildCount(); i++) {
View child = llTab.getChildAt(i);
child.setPadding(0, 0, 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
params.leftMargin = left;
params.rightMargin = right;
child.setLayoutParams(params);
child.invalidate();
}
由于水平太臭,就不多解释了…
至于使用方式的话,直接调用方法即可.必须要在Tablayout渲染出来后调用,我们可以选择view.post()方法来实现:
- tab.post(new Runnable() {
- @Override
- public void run() {
- setIndicator(tab,60,60);
- }
- });
tab.post(new Runnable() {
@Override
public void run() {
setIndicator(tab,60,60);
}
});
最后放上效果图: