Android设置Roboto字体,包括粗体、斜体、常规等(类似自定义字体系列)

5

我知道如何在Android应用程序中以编程方式设置自定义字体。

是否有一种方法可以为自定义字体(assets)加载typeface,并且Android框架将根据粗体、斜体等使用适当的文件?

例如,现在我正在尝试将Roboto字体设置为某些TextView

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
textView.setTypeface(typeface);

它可以正常工作。但是由于我在xml布局中将TextView设置为粗体,因此文本并没有加粗。

<TextView
    android:id="@+id/my_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:layout_marginTop="50dp"
    android:textStyle="bold"
    android:gravity="center"
    android:text="@string/my_text"
    android:textColor="@color/my_foreground"
    android:textSize="24dp" />

如何正确从资产中加载字体以使其正常工作?
textView.setTypeface(typeface, Typeface.BOLD);

我的资源文件夹里只有一个“字体家族”

Roboto-Black.ttf
Roboto-BlackItalic.ttf
Roboto-Bold.ttf
Roboto-BoldCondensed.ttf
Roboto-BoldCondensedItalic.ttf
Roboto-BoldItalic.ttf
Roboto-Condensed.ttf
Roboto-CondensedItalic.ttf
Roboto-Italic.ttf
Roboto-Light.ttf
Roboto-LightItalic.ttf
Roboto-Medium.ttf
Roboto-MediumItalic.ttf
Roboto-Regular.ttf
Roboto-Thin.ttf
Roboto-ThinItalic.ttf

如何将所有字体加载到一个字体/系列中?
2个回答

3

1
看起来不错,但格式有问题。为什么不在这里粘贴相同的类? - mente
1
链接已损坏。 - chossen-addict
对不起,这个网站已经停止运行多年了。 您现在可以使用Android数据绑定来使用任何类型的字体。 - AAverin

2
我不知道如何将单个字体的不同变体视为一个字体族,但是字体往往具有较大的文件大小,因此您可能不想将所有这些字体导入到应用程序中。相反,您可以仅使用Medium字体,然后设置粗体和斜体属性。
例如,如果您在XML布局中设置了android:textStyle =“bold”,则可以在代码中执行以下操作以保留粗体样式:
Typeface currentTypeFace = textView.getTypeface();
if (currentTypeFace != null && currentTypeFace.getStyle() == Typeface.BOLD) {
    textView.setTypeface(tf, Typeface.BOLD);
} else {
    textView.setTypeface(tf);
}

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