如何在Android的TextView中使用Open Sans字体样式?默认情况下,Open Sans
字体系列不可用。
Android O和Android Support Library 26支持可下载字体。
谷歌字体在Google Play服务中提供字体提供程序。
使用这个库可以改变整个应用程序的字体 Calligraphy
使用此代码可以更改特定文本的字体。
将字体文件放置在资产文件夹中。在我的情况下,我创建了一个名为fonts的子目录。
TextView tv = (TextView) findViewById(R.id.textViewName);
Typeface face = Typeface.createFromAsset(getAssets(),"fonts/opansans.ttf");
tv.setTypeface(face);
public class LotaRegularTextView extends TextView {
public LotaRegularTextView(Context context) {
super(context);
this.setTypeface(Typeface.SERIF);
}
public LotaRegularTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setTypeface(Typeface.SERIF);
}
public LotaRegularTextView(Context context, AttributeSet attrs, int
defStyleAttr) {
super(context, attrs, defStyleAttr);
this.setTypeface(Typeface.SERIF);
}
}
public final class FontsOverride {
public static void setDefaultFont(Context context,
String staticTypefaceFieldName, String fontAssetName) {
final Typeface regular = Typeface.createFromAsset(context.getAssets(),
fontAssetName);
replaceFont(staticTypefaceFieldName, regular);
}
protected static void replaceFont(String staticTypefaceFieldName,
final Typeface newTypeface) {
try {
final Field staticField = Typeface.class
.getDeclaredField(staticTypefaceFieldName);
staticField.setAccessible(true);
staticField.set(null, newTypeface);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
FontsOverride.setDefaultFont(this, "SERIF", "fonts/Lato-Regular.ttf");
<com.example.widget.LotaRegularTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/padding10"
android:text="Ashish"
android:textColor="@color/gini_gray_color_7d7d7d"
android:textSize="@dimen/s_common_a"/>
您必须添加自定义字体。首先下载字体存档 .ttf,您可以在以下链接中找到:https://www.fontsquirrel.com/fonts/open-sans。一旦您拥有它,我建议您使用此教程添加自定义字体:https://futurestud.io/tutorials/custom-fonts-on-android-using-font-styles