自定義Tab下劃線成都簡單 定死版

/**
 * 經過反射機制 修改TableLayout 的下劃線長度
 */

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);
    //得到tabview
    LinearLayout llTab = null;
    try {
        llTab = (LinearLayout) tabStrip.get(tabs);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    //設置tabView的padding爲0,而且設置了margin
    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();
    }
}

 

調用app

兩個參數是左 右。ide

//            設置下劃線長度
            homeFragment_tab.post(new Runnable() {
                @Override
                public void run() {
                    setIndicator(homeFragment_tab,20,20);
                }
            });
相關文章
相關標籤/搜索