字體資源定義可在應用中使用的自定義字體。字體可以是單獨的字體文件或字體文件的集合,稱爲字體系列,並在 XML 中定義。
1.自定義字體
1.1.文件位置
res/font/filename.ttf
(.ttf
、.ttc
、.otf
或 .xml
)
該文件名將用作資源 ID。
1.2.資源引用
在 XML 中:@[package:]font/font_name
1.3.語法
<?xml version="1.0" encoding="utf-8"?>
<font-family>
<font
android:font="@[package:]font/font_to_include"
android:fontStyle=["normal" | "italic"]
android:fontWeight="weight_value" />
</font-family>
1.4.示例
保存於 res/font/lobster.xml
的 XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="@font/lobster_regular" />
<font
android:fontStyle="italic"
android:fontWeight="400"
android:font="@font/lobster_italic" />
</font-family>
應用字體:
<?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!" />
2.下載字體
2.1.文件位置
res/font/filename.xml
該文件名用作資源 ID。
2.2.資源引用
在 XML 中:@[package:]font/font_name
2.3.語法
<?xml version="1.0" encoding="utf-8"?>
<font-family
android:fontProviderAuthority="authority"
android:fontProviderPackage="package"
android:fontProviderQuery="query"
android:fontProviderCerts="@[package:]array/array_resource" />
- android:fontProviderAuthority:必需。定義字體請求的字體提供程序的授權。
- android:fontProviderPackage:必需。要用於請求的字體提供程序的軟件包名稱。此屬性用於驗證提供程序的身份。
- android:fontProviderQuery:必需。字體的字符串查詢。
- android:fontProviderCerts:數組資源。必需。定義用於爲此提供程序簽名的證書的哈希集。此屬性用於驗證提供程序的身份,僅當提供程序不屬於系統映像的一部分時纔是必需的。該值可以指向單個列表(字符串數組資源)或列表的列表(數組資源),其中每個單獨的列表代表一個簽名哈希集合。
2.4.示例
保存於 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!" />