Android 8.0 (API 26)提供了一个新特性,即在xml定义字体。意味着字体作为一种资源的形式存在。我们将字体文件(.ttf或.otf)添加到res/font/文件夹中,将字体捆绑为资源。这些字体会在R 文件中被编译,并在 Android Studio 中自动提供。我们可以通过@font/myfont在布局文件中使用,或R.font.myfont在Java中使用。为了能够在Android 4.1(API 16)的设备上使用这个新特性,我们的应用app要加入Support Library 26库。 那么我们以是否有Support Library 26库作为分界线来讨论字体的使用问题。
新建Assets及fonts目录,并将字体文件拷贝到fonts目录下 在java代码中使用:
TextView mTV = findViewById(R.id.tv); Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/华文彩云.TTF"); mTV.setTypeface(typeface);新建资源目录font,并将字体文件拷贝到font目录下: (注意 :资源文件名都要求用小写的英文字命名) 在布局文件中使用:
<TextView android:fontFamily="@font/pop" android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content"/>在java中使用:
TextView mTV = findViewById(R.id.tv); Typeface typeface = ResourcesCompat.getFont(this,R.font.pop); mTV.setTypeface(typeface);这种方式是不把字体文件放在本地,而是在需要时,去网络上请求。
保存于 res/font/lobster.xml 的 XML 文件:
<?xml version="1.0" encoding="utf-8"?> <font-family xmlns:android="http://schemas.android.com/apk/res/android" android:fontProviderAuthority="com.example.fontprovider.authority" android:fontProviderPackage="com.example.fontprovider" android:fontProviderQuery="Lobster" android:fontProviderCerts="@array/certs"> </font-family>定义证书数组的 XML 文件保存在 res/values/ 中:
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="certs"> <item>MIIEqDCCA5CgAwIBAgIJA071MA0GCSqGSIb3DQEBBAUAMIGUMQsww...</item> </string-array> </resources>应用字体:
<?xml version="1.0" encoding="utf-8"?> <EditText android:fontFamily="@font/lobster" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, World!" />