使用半粗体样式的可下载Android字体

5

我正在使用以下链接中提供的谷歌可下载字体:

https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts.html

我想使用Montserrat字体样式的半粗体,但是在Android中没有该选项。

另外,在下面的链接中有半粗体样式,请问如何实现?

https://fonts.google.com/specimen/Montserrat

以下是我添加了字体族之后的TextView XML:

 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="@font/montserrat"
        android:text="@string/address"
        android:textAllCaps="false"
        android:textColor="@color/title_light_color"
        android:textSize="10sp"
        android:textStyle="bold" />

你在 FontRequest 的查询参数中发送的字体名称是什么?是 "Montserrat-SemiBold.ttf" 吗?请参考:https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts#programmatically - ashishdhiman2007
4个回答

2

2
您可以在res/font中创建新的字体:
<?xml version="1.0" encoding="utf-8"?>
<font-family
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:fontProviderAuthority="com.google.android.gms.fonts"
    app:fontProviderPackage="com.google.android.gms"
    app:fontProviderQuery="name=Montserrat&amp;weight=600"
    app:fontProviderCerts="@array/com_google_android_gms_fonts_certs">
</font-family>

您可以通过更改app:fontProviderQuery中的weight(半粗体为600)来指定任何支持的字重。Android Studio将会引发FontValidationWarning,但是它仍然能够正常工作。
来源:Google Fonts API for Android documentation

0
创建一个名为FontCache的类:
import android.content.Context;
import android.graphics.Typeface;
import java.util.Hashtable;

public class FontCache {
    private static Hashtable<String, Typeface> fontCache = new Hashtable<>();

    public static Typeface get(String name, Context context) {
        Typeface tf = fontCache.get(name);

        if (tf == null) {
            try {
                tf = Typeface.createFromAsset(context.getAssets(), name);
            } catch(Exception e) {
                return null;
            }

            fontCache.put(name, tf);
        }

        return tf;
    }
}

然后将以下代码行放入您的活动中:

Typeface montserratFontType = FontCache.get("fonts/montserrat.ttf", MainActivity.this);
yourTextView.setTypeface(montserratFontType);

最后,在您的主文件夹内创建一个名为assets的文件夹,然后在assets文件夹内创建一个名为fonts的文件夹,并将您的montserrat.ttf文件放入其中。

0

试试这个,为Android应用程序创建自定义字体样式,

首先创建assets文件夹,然后在其中创建font文件夹,将下载的字体(例如:Light.ttf)放入其中输入链接描述

然后在活动中添加此行:

Typeface mycustomface1 = Typeface.createFromAsset(context.getAssets(), "fonts/Light.ttf");

然后声明那个TextView

textview.setTypeface(mycustomface1);

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