Android TabLayout自定义指示器宽度

14

我想缩小指示器的宽度 - 例如,不让它的宽度与选项卡的整个宽度相同,而是只有选项卡宽度的1/2。

这就是我想做的全部内容,所以我不想下载一些自定义库并搜索我可以在哪里做到这一点。

是否有方法可以实现这一点,还是我应该自己编写视图?


1
这个答案对我非常有效。 - sudhakara k s
5个回答

25

如果您想要一个固定大小的选项卡指示器,可以通过drawable创建一个具有固定大小的指示器形状来实现:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="center">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorAccent" />
            <corners
                android:topLeftRadius="2dp"
                android:topRightRadius="2dp" />
            <size
                android:width="16dp"
                android:height="2dp" />
        </shape>
    </item>
</layer-list>

然后在TabLayout上,您只需要设置选项卡指示器的可绘制元素。 同时,您还需要设置tabIndicatorColor

 app:tabIndicatorColor="@color/tabIndicatorColor"
 app:tabIndicator="@drawable/tab_indicator"

由于可绘制对象本身会将形状居中在其边界内,指示器的大小将是固定的。

如果您希望指示器与标签的宽度匹配,则可以删除tabIndicator android:gravity

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/colorAccent" />
            <corners
                radius="2dp" />
            <size
                android:width="16dp"
                android:height="2dp" />
        </shape>
    </item>
</layer-list>

1
这是最干净的解决方案!我曾经用9-patch PNG解决过,但这个肯定更好。我尝试过类似的解决方案,但是缺少了默认的gravity值是fill... - Massimo

15

如果有人遇到这个问题,我找到了一个简单的解决方案,使用矢量可绘制对象可以实现标签宽度指示器的大约90%:

ic_tab_indicator_24dp:

<vector
android:height="24dp"
android:width="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0"
xmlns:android="http://schemas.android.com/apk/res/android">
<path
    android:strokeWidth="4"
    android:fillColor="@android:color/white"
    android:pathData="M2,0 L22,0 L22,24 L2,24 z"/>

然后在布局中设置tabIndicator:

app:tabIndicator="@drawable/ic_tab_indicator_24dp"

或者在styles.xml中:

<item name="tabIndicator">@drawable/ic_tab_indicator_24dp</item>

Example

编辑:由于我的解决方案引起了关注,我想补充一下,您可以通过修改pathData(“M2,0 L22,0 L22,24 L2,24 z”)来调整宽度,改变2和22的值。从2中添加的量应从22中减去。例如:“M4,0 L20,0 L20,24 L4,24 z”或“M6,0 L18,0 L18,24 L6,24 z”...


2
这个逻辑太棒了! - Yyy

3

试试这个。

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);  
   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();  
   }  
}

然后。
tab.post(new Runnable() {  
       @Override  
       public void run() {  
           setIndicator(tab,60,60);  
       }  
});  


没有使用反射的修改(必须设置自定义视图!)。

for (int i = 0; i < tabs.getTabCount(); i++) {
    TabLayout.Tab tab = tabs.getTabAt(i);
    if (tab != null) {
        View customView = tab.getCustomView();
        if (customView != null) {
            View targetViewToApplyMargin = (View) customView.getParent();
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) targetViewToApplyMargin.getLayoutParams();

            layoutParams.rightMargin = totalTabMargin;
                    targetViewToApplyMargin.setLayoutParams(layoutParams);
        }
    }
}

非常感谢!我稍微修改了你的答案(使用自定义视图,没有反射),但是你的方向绝对是正确的! - Goltsev Eugene
感谢您的修改,我明天会尝试一下。@GoltsevEugene - KeLiuyue
gre8-> 对我来说运行良好,谢谢。 - Bhavesh Rangani
@GoltsevEugene,可以告诉我如何设置自定义视图以及你设置的内容是什么吗? - Gurupad Mamadapur
yourTabs.getTabAt(tabIndex).setCustomView(yourView)。请返回翻译后的文本。 - Goltsev Eugene
显示剩余2条评论

3

尝试了所有这些解决方案,但都不满意,最终我找到了一个解决方案。我们只需要修改SlidingTabIndicator的indicatorLeft和indicatorRight属性,扩展tablayout并在需要时调用setIndicaotrWidth()方法即可,例如:

setIndicatorWidth(70);

完整的代码如下:

import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;

import java.lang.reflect.Field;

import androidx.annotation.NonNull;

public class TabLayoutEx extends TabLayout {

    public TabLayoutEx(Context context) {
        this(context, null);
    }

    public TabLayoutEx(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TabLayoutEx(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        setTabIndicatorFullWidth(false);
        setIndicatorWidth(70);
    }



    private class DefPreDrawListener implements ViewTreeObserver.OnPreDrawListener {

        private LinearLayout tabStrip = null;
        private int tabWidth;
        private Field fieldLeft;
        private Field fieldRight;

        public void setTabStrip(LinearLayout tabStrip, int width) {
            try {
                this.tabStrip = tabStrip;
                this.tabWidth = width;
                Class cls = tabStrip.getClass();
                fieldLeft = cls.getDeclaredField("indicatorLeft");
                fieldLeft.setAccessible(true);
                fieldRight = cls.getDeclaredField("indicatorRight");
                fieldRight.setAccessible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean onPreDraw() {
            try {
                if (tabWidth > 0) {
                    int left = fieldLeft.getInt(this.tabStrip);
                    int right = fieldRight.getInt(this.tabStrip);
                    //根据目标宽度及现在的宽度调整为合适的left和right
                    int diff = right - left - tabWidth;
                    left = left + diff / 2;
                    right = right - diff / 2;
                    fieldLeft.setInt(this.tabStrip, left);
                    fieldRight.setInt(this.tabStrip, right);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
    }

    private DefPreDrawListener defPreDrawListener = new DefPreDrawListener();

    public void setIndicatorWidth(int widthDp) {
        Class<?> tabLayout = TabLayout.class;
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("slidingTabIndicator");
            tabStrip.setAccessible(true);
            LinearLayout tabIndicator = (LinearLayout) tabStrip.get(this);
            int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, widthDp, Resources.getSystem().getDisplayMetrics());
            //avoid add preDrawListener multi times
            tabIndicator.getViewTreeObserver().removeOnPreDrawListener(defPreDrawListener);
            tabIndicator.getViewTreeObserver().addOnPreDrawListener(defPreDrawListener);
            defPreDrawListener.setTabStrip(tabIndicator, width);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}


使用这段代码后,选项卡指示器的宽度位于中心,但我想要它在左侧,并且希望其大小为文本的一半。那么该怎么办? - Kinjal Shah

1
您可以复制TabLayout,并修改计算Indicator宽度的逻辑。请查看updateIndicatorPosition()和animateIndicatorToPosition()方法。这里有一个简单的演示:https://github.com/xybean/CustomTabLayout

1
这更像是建议而不是完整的答案。您能提供一下实现您想法的示例吗?如果您能添加一些细节,那就太好了。谢谢! - Yazon2006
我尝试的理想情况是复制所有这些类 - ViewPager、TabLayout等,以实现完全可定制的行为。问题在于,当复制时,有很多私有/本地字段无法导入到项目中。此外,所有这些类都与支持包中的其他类有非常强的连接。所以对我来说真的很难做到这一点。 - Goltsev Eugene
@GoltsevEugene 只需复制 TabLayout。 - Shayabean
@Yazon2006 我已经将一个演示上传到Github,请查看 https://github.com/xybean/CustomTabLayout - Shayabean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接