安卓自定义字体的几种方式 - 知乎
方式一
使用API提供的默认字体,有以下几种:
noraml (普通字体,系统默认使用的字体)
sans(非衬线字体)
serif (衬线字体)
monospace(等宽字体)
xml中TextView设置:
android:typeface="monospace"
java代码TextView设置:
myText.setTypeface(Typeface.MONOSPACE);
方式二
在工程目录src/main下,创建一个assets/font文件夹,把字体文件放入文件夹中,如图:
java代码TextView设置:
Typeface typeface = Typeface.createFromAsset(getAssets(), "font/opposans.ttf");
myTextView.setTypeface(typeface);
方式三
安卓8.0后,在工程目录res下,创建一个font文件夹,把字体文件放入文件夹中,如图:
xml中TextView设置:
android:fontFamily="@font/opposans"
java代码TextView设置:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Typeface typeface = getResources().getFont(R.font.opposans);
myTextView.setTypeface(typeface);
}
如果想整个activity界面都使用此字体,旧版AS工程在res/values/styles.xml中,新版AS工程在res/values/themes.xml中加入如下style
<style name="MyFont" parent="AppTheme">
<item name="android:fontFamily">@font/opposans</item>
</style>
manifest.xml中
<activity
android:name=".MainActivity"
android:theme="@style/MyFont" />
如果想整个APP界面都使用此字体,在manifest.xml中
<application
android:theme="@style/AppTheme">
styles.xml或者themes.xml中
<style name="AppTheme" parent="xxx">
<item name="android:fontFamily">@font/opposans</item>
</style>
更多API调用参考官网地址:https://developer.android.google.cn/reference/android/graphics/Typeface?hl=en#getStyle()
字体下载推荐:https://fonts.google.com/