android TabLayout 设置字体
时间: 2024-04-15 17:26:34 浏览: 168
要在Android TabLayout上设置字体,你可以使用自定义的TabLayout.TabCustomView来实现。以下是一个示例代码:
首先,在res/layout目录下创建一个自定义的tab_item.xml文件,用于定义TabLayout中每个标签的样式,可以在此文件中设置字体样式。
```xml
<!-- tab_item.xml -->
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="@color/tab_text_color"
android:fontFamily="@font/custom_font" />
```
接下来,在你的Activity或Fragment中,使用以下代码来设置TabLayout的标签视图:
```java
// 获取TabLayout对象
TabLayout tabLayout = findViewById(R.id.tab_layout);
// 添加标签
tabLayout.addTab(tabLayout.newTab().setCustomView(R.layout.tab_item));
// 设置标签文本
TextView tabText = tabLayout.getTabAt(0).getCustomView().findViewById(R.id.tab_text);
tabText.setText("标签1");
```
在上面的代码中,你可以看到通过调用`setCustomView()`方法来设置自定义的布局文件作为标签视图。然后,我们可以通过`getCustomView()`方法获取自定义视图,并使用findViewById()来找到TextView并设置文本。
请注意,你需要将自定义字体文件放在res/font目录下,并将其引用到tab_item.xml中的`android:fontFamily`属性中。
这样就可以在Android TabLayout上设置字体了。你可以根据需要自定义标签视图,并在其中设置不同的字体样式。
阅读全文
相关推荐















