優雅地修改 TabLayout 指示線 Indicator 的寬度

在工做中,常常會碰到把標籤欄指示線的寬度,作的和文字寬度同樣,甚至比文字寬度還要短的設計。使用 TabLayout 咱們能夠快速實現一個 Material Design 風格的標籤欄,但 TabLayout 的指示線 Indicator 默認是佔滿一格 Tab 的,且未直接提供修改 Indicator 寬度的方法。php

本文總結了幾種修改 Indicator 寬度的方案,並討論如何「優雅」地修改它。java

反射

若是你的項目中也有修改指示線寬度的需求,而且已經在網上找過修改方法,極可能你如今項目中用的就是這個方法。網上大部分文章都是經過分析源碼,用反射實現的,代碼以下:android

public void setIndicatorWidth(@NonNull final TabLayout tabLayout, final int margin) {
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip");
                    mTabStripField.setAccessible(true);
                    LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout);
                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);
                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        tabView.setPadding(0, 0, 0, 0);
                        int width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = margin;
                        params.rightMargin = margin;
                        tabView.setLayoutParams(params);
                        tabView.invalidate();
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }
複製代碼

這樣作是沒問題的,但若是把項目的 SDK 升級到 28 或以上,它就再也不有效了,緣由是 TabLayout 源碼中的變量名修改了,因此代碼也要改爲這樣:app

public void setIndicatorWidth(@NonNull final TabLayout tabLayout, final int margin) {
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    Field slidingTabIndicatorField = tabLayout.getClass().getDeclaredField("slidingTabIndicator");
                    slidingTabIndicatorField.setAccessible(true);
                    LinearLayout mTabStrip = (LinearLayout) slidingTabIndicatorField.get(tabLayout);
                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);
                        Field textViewField = tabView.getClass().getDeclaredField("textView");
                        textViewField.setAccessible(true);
                        TextView mTextView = (TextView) textViewField.get(tabView);
                        tabView.setPadding(0, 0, 0, 0);
                        int width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = margin;
                        params.rightMargin = margin;
                        tabView.setLayoutParams(params);
                        tabView.invalidate();
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }
複製代碼

經過反射雖然能夠實現,但我我的以爲反射不夠優雅,而且它有可能由於 SDK 的升級而失效。ide

自定義 Tab

TabLayout 中的 Tab 是容許自定義的,但 Indicator 不屬於 Tab。佈局

因此有這樣一種解決方案,把 Indicator 隱藏掉,而後在自定義 Tab 的佈局中加入指示線。post

咱們能夠經過把 Indicator 的顏色設爲透明來隱藏它:動畫

<android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabIndicatorColor="@android:color/transparent" />
複製代碼

在代碼中,當 Tab 添加完畢後,替換成自定義的 Tab:spa

TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(R.layout.layout_tab);
TextView tv = tab.getCustomView().findViewById(R.id.text_view);
tv.setText(tab.getText());
複製代碼

而且還須要監聽 Tab 的切換,控制指示線的顯示隱藏:設計

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        // TODO Tab 被切換,刷新全部 Tab
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
});
複製代碼

用這種方法,什麼樣式都能實現了。但有個缺點是,在 Tab 切換的時候,沒有了指示線的移動動畫。

SDK 28+ 屬性配置

若是你使用的 SDK 版本是 28 或以上,而且須要將 Indicator 的寬度修改爲和文字寬度同樣,那麼太棒了,如今你只須要給 TabLayout 配置一個屬性就行了:

<android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabIndicatorFullWidth="false" />
複製代碼

當 tabIndicatorFullWidth 取 false 的時候,Indicator 的寬度會和文字的寬度同樣,但這也意味着,當不一樣 Tab 裏的文字寬度不同時,Indicator 的寬度也會不同,像下面這樣。

若是設計要求 Indicator 的寬度必須固定,或者寬度要比文字短,那咱們還要接着找別的解決方案。

使用 Drawable 樣式

最後這種方案,是我認爲最優雅的解決方案,使用也特別簡單。在網上還沒看到有人使用,能夠算是個人原創了,哈哈。

Indicator 是容許咱們設置 drawable 來自定義樣式的,好比添加圓角什麼的。但不管什麼樣式,Indicator 依然是佔滿 Tab 寬度的。不要緊,咱們把它的背景設成透明,包含一個固定寬度的 shape 就行了,像這樣:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">

    <item android:gravity="center">
        <shape>

            <size android:width="16dp" android:height="4dp" />

            <corners android:radius="4dp" />

            <solid android:color="@color/colorAccent" />

        </shape>
    </item>

</layer-list>
複製代碼

而後在佈局文件中配置 tabIndicator 屬性:

<android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabIndicatorHeight="10dp" app:tabIndicator="@drawable/tab_indicator" />
複製代碼

也能夠在代碼中設置:

tabLayout.setSelectedTabIndicator(R.drawable.tab_indicator);
複製代碼

效果以下:

從上面這個例子還能夠發現,使用這個方法,不只能夠在視覺上增長 Indicator 的左右邊距,還能夠增長它的上下邊距。

好啦,其實就是配置一個 Drawable 文件這麼簡單,只是發現網上很多人在問,但尚未人用這個方法解決,在這裏和你們分享一下。

相關文章
相關標籤/搜索