130

我正在尝试TabLayout使用 android 设计库中的新功能。

我想将标签文本更改为自定义字体。而且,我试图搜索一些与 相关的样式TabLayout,但最终得到了这个

请指导如何更改选项卡文本字体。

4

19 回答 19

173

如果您正在使用TabLayout并且想要更改字体,则必须向以前的解决方案添加一个新的 for 循环,如下所示:

private void changeTabsFont() {
    ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
        int tabsCount = vg.getChildCount();
        for (int j = 0; j < tabsCount; j++) {
            ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
            int tabChildsCount = vgTab.getChildCount();
            for (int i = 0; i < tabChildsCount; i++) {
                View tabViewChild = vgTab.getChildAt(i);
                if (tabViewChild instanceof TextView) {
                    ((TextView) tabViewChild).setTypeface(Font.getInstance().getTypeFace(), Typeface.NORMAL);
                }
        }
    }
} 

请参阅使用 sherlock 更改操作栏选项卡中的字体样式

于 2015-06-26T07:28:11.487 回答
138

创建您自己的自定义样式并将父样式用作parent="@android:style/TextAppearance.Widget.TabWidget"

在你的标签布局中使用这种风格作为app:tabTextAppearance="@style/tab_text"

示例:样式:

<style name="tab_text" parent="@android:style/TextAppearance.Widget.TabWidget">
    <item name="android:fontFamily">@font/poppins_regular</item>
</style>

示例:选项卡布局组件:

<android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:tabTextAppearance="@style/tab_text" />
于 2017-08-22T11:51:08.163 回答
49

praveen Sharma 给出了很好的回答。只是一个小补充:changeTabsFont()TabLayout可以简单地使用自己的CustomTabLayout.

import android.content.Context;
import android.graphics.Typeface;
import android.support.design.widget.TabLayout;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class CustomTabLayout extends TabLayout {
    private Typeface mTypeface;

    public CustomTabLayout(Context context) {
        super(context);
        init();
    }

    public CustomTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

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

    private void init() {
        mTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf");
    }

    @Override
    public void addTab(Tab tab) {
        super.addTab(tab);

        ViewGroup mainView = (ViewGroup) getChildAt(0);
        ViewGroup tabView = (ViewGroup) mainView.getChildAt(tab.getPosition());

        int tabChildCount = tabView.getChildCount();
        for (int i = 0; i < tabChildCount; i++) {
            View tabViewChild = tabView.getChildAt(i);
            if (tabViewChild instanceof TextView) {
                ((TextView) tabViewChild).setTypeface(mTypeface, Typeface.NORMAL);
            }
        }
    }

}

还有一件事情。 TabView是一个LinearLayoutwith TextViewinside(它也可以选择包含ImageView)。因此,您可以使代码更加简单:

@Override
public void addTab(Tab tab) {
    super.addTab(tab);

    ViewGroup mainView = (ViewGroup) getChildAt(0);
    ViewGroup tabView = (ViewGroup) mainView.getChildAt(tab.getPosition());
    View tabViewChild = tabView.getChildAt(1);
    ((TextView) tabViewChild).setTypeface(mTypeface, Typeface.NORMAL);
}

但我不会推荐这种方式。如果TabLayout实现发生变化,则此代码可能无法正常工作甚至崩溃。

另一种自定义方法TabLayout是向其添加自定义视图。这是一个很好的例子

于 2015-10-22T15:37:24.283 回答
39

像这样从 Java 代码或 XML 创建一个 TextView

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:textSize="15sp"
    android:textColor="@color/tabs_default_color"
    android:gravity="center"
    android:layout_height="match_parent"
/>

确保保持 id 原样,因为如果您使用自定义 textview,TabLayout 会检查此 ID

然后从代码中扩展此布局并Typeface在该 textview 上设置自定义并将此自定义视图添加到选项卡

for (int i = 0; i < tabLayout.getTabCount(); i++) {
     //noinspection ConstantConditions
     TextView tv = (TextView)LayoutInflater.from(this).inflate(R.layout.custom_tab,null)
     tv.setTypeface(Typeface);       
     tabLayout.getTabAt(i).setCustomView(tv);
}
于 2017-07-31T06:57:27.157 回答
28

XML要在运行(API 级别 16)及更高版本的设备上使用功能中的字体支持Android 4.1,请使用支持库 26+。

  1. 右键单击 res 文件夹
  2. 新建->Android资源目录->选择字体->确定
  3. 将您的myfont.ttf文件放在新创建的字体文件夹中

添加res/values/styles.xml时:

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/myfont</item>
</style>

在布局文件上添加 app:tabTextAppearance="@style/customfontstyle",

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="fill"
    app:tabTextAppearance="@style/customfontstyle"
    app:tabMode="fixed" />

请参考 [xml 中的字体]。( https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml )

于 2018-08-14T06:12:26.280 回答
17

如果您正在使用

com.google.android.material:material:1.2.0(最新版本)

<style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="fontFamily">Your Font</item>
        <item name="android:fontFamily">Your Font</item>
        <item name="textAllCaps">false</item>
    </style>

<com.google.android.material.tabs.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabBackground="@color/colorPrimary"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/white"
        app:tabMode="fixed"
        app:tabTextAppearance="@style/MyCustomTabTextAppearance"
        app:tabTextColor="@android:color/white" />
于 2020-10-09T20:08:23.240 回答
16

以下方法将ViewGroup递归更改整个字体。我选择这种方法是因为你不必关心TabLayout. 我正在使用书法库来设置字体。

void changeFontInViewGroup(ViewGroup viewGroup, String fontPath) {
    for (int i = 0; i < viewGroup.getChildCount(); i++) {
        View child = viewGroup.getChildAt(i);
        if (TextView.class.isAssignableFrom(child.getClass())) {
            CalligraphyUtils.applyFontToTextView(child.getContext(), (TextView) child, fontPath);
        } else if (ViewGroup.class.isAssignableFrom(child.getClass())) {
            changeFontInViewGroup((ViewGroup) viewGroup.getChildAt(i), fontPath);
        }
    }
}
于 2016-04-22T14:59:40.043 回答
10

正如安德烈回答的那样,您可以通过扩展TabLayout类来更改字体。正如Penzzz所说,你不能在addTab方法中做到这一点。重写onLayout方法如下:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom){
    super.onLayout(changed, left, top, right, bottom);

    final ViewGroup tabStrip = (ViewGroup)getChildAt(0);
    final int tabCount = tabStrip.getChildCount();
    ViewGroup tabView;
    int tabChildCount;
    View tabViewChild;

    for(int i=0; i<tabCount; i++){
        tabView = (ViewGroup)tabStrip.getChildAt(i);
        tabChildCount = tabView.getChildCount();
        for(int j=0; j<tabChildCount; j++){
            tabViewChild = tabView.getChildAt(j);
            if(tabViewChild instanceof AppCompatTextView){
                if(fontFace == null){
                    fontFace = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.IranSans));
                }
                ((TextView) tabViewChild).setTypeface(fontFace, Typeface.BOLD);
            }
        }
    }
}

必须覆盖 onLayout 方法,因为当您使用setupWithViewPager方法将 TabLayout 与 ViewPager 绑定时,您必须使用 setText 方法或在之后的 PagerAdapter 中设置选项卡文本,当这种情况发生时,onLayout 方法会在父 ViewGroup 上调用( TabLayout),这就是设置字体的地方。(更改 TextView 文本会导致调用其父级的 onLayout 方法 - tabView 有两个子级,一个是 ImageView 另一个是 TextView)

另一个解决方案:

首先,这些代码行:

    if(fontFace == null){
        fontFace = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.IranSans));
    }

在上面的解决方案中,应该写在两个循环之外。

但API >= 16的更好解决方案是使用android:fontFamily

创建一个名为 font的Android 资源目录并将所需的字体复制到该目录。

然后使用这些样式:

<style name="tabLayoutTitles">
    <item name="android:textColor">@color/white</item>
    <item name="android:textSize">@dimen/appFirstFontSize</item>
    <item name="android:fontFamily">@font/vazir_bold</item>
</style>

<style name="defaultTabLayout">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">@dimen/defaultTabLayoutHeight</item>
    <item name="android:gravity">right</item>
    <item name="tabTextAppearance">@style/tabLayoutTitles</item>
    <item name="tabSelectedTextColor">@color/white</item>
    <item name="tabIndicatorColor">@color/white</item>
    <item name="tabIndicatorHeight">@dimen/accomTabIndicatorHeight</item>
    <item name="tabMode">fixed</item>
    <item name="tabGravity">fill</item>
    <item name="tabBackground">@drawable/rectangle_white_ripple</item>
    <item name="android:background">@color/colorPrimary</item>
</style>
于 2017-04-22T18:10:30.300 回答
10

对于设计支持 23.2.0,使用 setupWithViewPager,您必须将代码从 addTab(Tab tab) 移动到 addTab(Tab tab, boolean setSelected)。

于 2016-03-07T18:37:43.463 回答
8

你可以用这个,它对我有用。

 private void changeTabsFont() {
    ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
    int tabsCount = vg.getChildCount();
    for (int j = 0; j < tabsCount; j++) {
        ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
        int tabChildsCount = vgTab.getChildCount();
        for (int i = 0; i < tabChildsCount; i++) {
            View tabViewChild = vgTab.getChildAt(i);
            if (tabViewChild instanceof TextView) {
                AssetManager mgr = getActivity().getAssets();
                Typeface tf = Typeface.createFromAsset(mgr, "fonts/Roboto-Regular.ttf");//Font file in /assets
                ((TextView) tabViewChild).setTypeface(tf);
            }
        }
    }
}
于 2017-08-13T14:13:40.410 回答
7

好吧,我发现它在 23.4.0 中很简单,没有使用循环。只需按照@ejw 的建议覆盖 addTab(@NonNull Tab tab, boolean setSelected) 。

@Override
public void addTab(@NonNull Tab tab, boolean setSelected) {
    CoralBoldTextView coralTabView = (CoralBoldTextView) View.inflate(getContext(), R.layout.coral_tab_layout_view, null);
    coralTabView.setText(tab.getText());
    tab.setCustomView(coralTabView);

    super.addTab(tab, setSelected);
}

这是XML

<?xml version="1.0" encoding="utf-8"?>
<id.co.coralshop.skyfish.ui.CoralBoldTextView
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/custom_text"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:ellipsize="end"
   android:gravity="center"
   android:singleLine="true"
   android:textColor="@color/graylove"
   android:textSize="@dimen/tab_text_size" />

希望它可以帮助:)

于 2016-05-26T12:25:23.807 回答
4

对我有用的 Kotlin 扩展:

fun TabLayout.setFont(font: FontUtils.Fonts) {
    val vg = this.getChildAt(0) as ViewGroup
    for (i: Int in 0..vg.childCount) {
        val vgTab = vg.getChildAt(i) as ViewGroup?
        vgTab?.let {
            for (j: Int in 0..vgTab.childCount) {
                val tab = vgTab.getChildAt(j)
                if (tab is TextView) {
                    tab.typeface = FontUtils.getTypeFaceByFont(FontUtils.Fonts.BOLD, context)
                }
            }
        }
    }
}
于 2018-09-02T14:07:47.677 回答
3
I think this is easier way.

<android.support.design.widget.TabLayout
   android:id="@+id/tabs"
   app:tabTextColor="@color/lightPrimary"
   app:tabSelectedTextColor="@color/white"
   style="@style/CustomTabLayout"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"/>
<style name="CustomTabLayout" parent="Widget.Design.TabLayout">
   <item name="tabMaxWidth">20dp</item>
   <item name="tabMode">scrollable</item>
   <item name="tabIndicatorColor">?attr/colorAccent</item>
   <item name="tabIndicatorHeight">2dp</item>
   <item name="tabPaddingStart">12dp</item>
   <item name="tabPaddingEnd">12dp</item>
   <item name="tabBackground">?attr/selectableItemBackground</item>
   <item name="tabTextAppearance">@style/CustomTabTextAppearance</item>
   <item name="tabSelectedTextColor">?android:textColorPrimary</item>
</style>
<style name="CustomTabTextAppearance" parent="TextAppearance.Design.Tab">
   <item name="android:textSize">16sp</item>
   <item name="android:textStyle">bold</item>
   <item name="android:textColor">?android:textColorSecondary</item>
   <item name="textAllCaps">false</item>
</style>
于 2018-08-17T15:30:09.097 回答
3

我的解决方法就是这样,更改指定的选项卡文本,

 ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
 ViewGroup vgTab = (ViewGroup) vg.getChildAt(1);
 View tabViewChild = vgTab.getChildAt(1);
 if (tabViewChild instanceof TextView) {
      ((TextView) tabViewChild).setText(str);
 }
于 2016-08-15T15:49:03.567 回答
2

这是我在 Kotlin 中的实现,它还允许更改选定和未选定选项卡的字体。

class FontTabLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    @AttrRes defStyleAttr: Int = 0
) : TabLayout(context, attrs, defStyleAttr) {

    private var textSize = 14f

    private var defaultSelectedPosition = 0

    private var selectedTypeFace: Typeface? = ResourcesCompat.getFont(context, R.font.muli_bold)
    private var normalTypeFace: Typeface? = ResourcesCompat.getFont(context, R.font.muli_regular)

    @ColorInt private var selectedColor = 0
    @ColorInt private var normalTextColor = 0

    init {
        attrs?.let { initAttrs(it) }
        addOnTabSelectedListener()
    }

    private fun initAttrs(attrs: AttributeSet) {
        val a = context.obtainStyledAttributes(attrs, R.styleable.FontTabLayout)

        textSize = a.getDimensionPixelSize(R.styleable.FontTabLayout_textSize, 14).toFloat()

        defaultSelectedPosition = a.getInteger(R.styleable.FontTabLayout_defaultSelectedPosition, 0)
        val selectedResourceId = a.getResourceId(R.styleable.FontTabLayout_selectedTypeFace, R.font.muli_bold)
        val normalResourceId = a.getResourceId(R.styleable.FontTabLayout_normalTypeFace, R.font.muli_regular)

        selectedColor = a.getColor(com.google.android.material.R.styleable.TabLayout_tabSelectedTextColor, 0)
        normalTextColor = a.getColor(R.styleable.FontTabLayout_normalTextColor, 0)

        selectedTypeFace = ResourcesCompat.getFont(context, selectedResourceId)
        normalTypeFace = ResourcesCompat.getFont(context, normalResourceId)

        a.recycle()
    }

    private fun addOnTabSelectedListener() {
        addOnTabSelectedListener(object : OnTabSelectedListenerAdapter() {

            override fun onTabUnselected(tab: Tab?) {
                getCustomViewFromTab(tab)?.apply {
                    setTextColor(normalTextColor)
                    typeface = normalTypeFace
                }
            }

            override fun onTabSelected(tab: Tab?) {

                getCustomViewFromTab(tab)?.apply {
                    setTextColor(selectedColor)
                    typeface = selectedTypeFace
                }
            }

            private fun getCustomViewFromTab(tab: Tab?) = tab?.customView as? AppCompatTextView

        })
    }

    override fun setupWithViewPager(viewPager: ViewPager?, autoRefresh: Boolean) {
        super.setupWithViewPager(viewPager, autoRefresh)
        addViews(viewPager)
    }

    private fun addViews(viewPager: ViewPager?) {
        for (i in 0 until tabCount) {
            val customTabView = getCustomTabView(i).apply {
                typeface = if (i == defaultSelectedPosition) selectedTypeFace else normalTypeFace
                val color = if (i == defaultSelectedPosition) selectedColor else normalTextColor
                setTextColor(color)
                text = viewPager?.adapter?.getPageTitle(i)
            }

            getTabAt(i)?.customView = customTabView
        }
    }

    private fun getCustomTabView(position: Int): AppCompatTextView {
        return AppCompatTextView(context).apply {
            gravity = Gravity.CENTER
            textSize = this@FontTabLayout.textSize
            text = position.toString()
        }
    }
}

在 attrs.xml 中:

<declare-styleable name="FontTabLayout">
    <attr name="normalTextColor" format="reference|color" />
    <attr name="textSize" format="dimension" />
    <attr name="defaultSelectedPosition" format="integer" />
    <attr name="selectedTypeFace" format="reference" />
    <attr name="normalTypeFace" format="reference" />
</declare-styleable>
于 2019-07-18T09:18:59.587 回答
1

我的 2p,带有参考检查的 Kotlin,适用于任何地方,因为如果出现问题,它将停止。

private fun setTabLayouFont(tabLayout: TabLayout) {
    val viewGroupTabLayout = tabLayout.getChildAt(0) as? ViewGroup?
    (0 until (viewGroupTabLayout?.childCount ?: return))
            .map { viewGroupTabLayout.getChildAt(it) as? ViewGroup? }
            .forEach { viewGroupTabItem ->
                (0 until (viewGroupTabItem?.childCount ?: return))
                        .mapNotNull { viewGroupTabItem.getChildAt(it) as? TextView }
                        .forEach { applyDefaultFontToTextView(it) }
            }
}
于 2018-02-28T11:10:43.817 回答
1

您可以使用 style.xml 文件中编写的此样式更改选项卡图标的文本外观。这里是

<style name="TabItemTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">13sp</item>
        <item name="fontWeight">800</item>
        <item name="fontFamily">@font/balooda2_medium</item>
</style>

并在您的 TabLayout 中使用此样式。这里是

<com.google.android.material.tabs.TabLayout
                android:id="@+id/live_tab_bar"
                android:layout_width="match_parent"
                android:layout_height="@dimen/_40sdp"
                app:tabGravity="fill"
                app:tabIndicatorGravity="stretch"
                app:tabMaxWidth="0dp"
                app:tabMode="fixed"
                app:tabSelectedTextColor="@color/white"
                app:tabTextAppearance="@style/TabItemTextAppearance"
                app:tabTextColor="#354895">

                <com.google.android.material.tabs.TabItem
                    android:id="@+id/live_tab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="লাইভ ক্লাস&quot; />

                <com.google.android.material.tabs.TabItem
                    android:id="@+id/recorded_tab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="রেকর্ডেড ভিডিও&quot; />

</com.google.android.material.tabs.TabLayout>
于 2021-08-10T07:53:41.940 回答
0

使用 kotlin 扩展函数使用:

 fun TabLayout.setFontSizeAndColor(typeface: Typeface, @DimenRes textSize: Int, @ColorRes textColor: Int) {
val viewGroup: ViewGroup = this.getChildAt(0) as ViewGroup
val tabsCount: Int = viewGroup.childCount
for (j in 0 until tabsCount) {
    val viewGroupTab: ViewGroup = viewGroup.getChildAt(j) as ViewGroup
    val tabChildCount: Int = viewGroupTab.childCount
    for (i in 0 until tabChildCount) {
        val tabViewChild: View = viewGroupTab.getChildAt(i) as View
        if ( tabViewChild is TextView) {
            tabViewChild.typeface = typeface
            tabViewChild.gravity = Gravity.FILL
            tabViewChild.maxLines = 1
            tabViewChild.setTextSize(TypedValue.COMPLEX_UNIT_PX, this.resources.getDimension(textSize))
            tabViewChild.setTextColor(ContextCompat.getColor(this.context, textColor))
        }
    }
}

}

于 2019-06-10T12:43:38.697 回答
-2

改变

if (tabViewChild instanceof TextView) {

为了

if (tabViewChild instanceof AppCompatTextView) { 

使其与 android.support.design.widget.TabLayout 一起工作(至少来自 com.android.support:design:23.2.0)

于 2016-03-04T09:14:35.097 回答