通過修改指示器的間距來改變TabLayout指示器的寬度
阿新 • • 發佈:2018-12-04
1.寫個工具類 封裝:
import android.content.res.Resources; import android.support.design.widget.TabLayout; import android.util.TypedValue; import android.view.View; import android.widget.LinearLayout; import java.lang.reflect.Field; /** * Created by Sy on 2017/05/08. * */ public class TabUtils { /*** @param tabs TabLayout * @param leftDip marginLeft * @param rightDip marginRight */ public static 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(); return; } tabStrip.setAccessible(true); LinearLayout llTab = null; try { llTab = (LinearLayout) tabStrip.get(tabs); } catch (IllegalAccessException e) { e.printStackTrace();
return; } 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(); } } }
2.在Activity呼叫
tab_view.post(new Runnable() { @Override public void run() { TabUtils.setIndicator(tab_view,10,10); } });3,此方法是通過反射獲取tablayout私有屬性進修改屬性值,如果app啟動混淆 會報NoSuchFieldException;
解決方案:在proguard-rules.pro混淆檔案中新增-keep class android.support.design.widget.TabLayout{*;}