TabLayout控件字体居中

一、找到对应的控件
tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
tabLayout.post(new Runnable() {
  @Override
  public void run() {
        setIndicator(tabLayout,60,60);
    }
});
二、实现setIndicator方法
public void setIndicator (TabLayout tabs,int leftDip,int rightDip){
    Class<?> tabLayout = tabs.getClass();
    java.lang.reflect.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();
    }
}


效果图

猜你喜欢

转载自blog.csdn.net/weikai_/article/details/79254420