1. 程式人生 > >TabLayout的一些特殊用法

TabLayout的一些特殊用法

一、給每一個tab中間新增分割線或圖示:

TabLayout繼承HorizontalScrollView,而HorizontalScrollView控制元件裡面只能有一個View,通過檢視原始碼TabLayout的子View是Linear Layout,而LinearLayout 自帶分割線

//LinearLayout自帶就有設定分割線的方法
LinearLayout layout =(LinearLayout)mTabLayout.getChildAt(0);
// 在所有子控制元件的中間顯示分割線(還可能只顯示頂部、尾部和不顯示分割線)
layout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
 // 設定分割線的距離本身(LinearLayout)的內間距
layout.setDividerPadding(20);
// 設定分割線的樣式
layout.setShowDividerDrawable(ContextCompat.getDrawable(context, R.drawable.divider_vertical));
設定分割線的樣式:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ccc"/>
    <size android:width="1dp" />
</shape>

二、通過反射設定Tab指示器的長度:

 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();
        }  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.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(tabLayout,60,60);
            }
        });