Androidでフォントを適用する方法をメモします。現在は fontFamily を使う方法が推奨されています。
現在の方法(fontFamily)
フォント配置
app/src/main/res/font/my_font.ttf
フォントを格納した後、以下の方法でフォントの適応範囲を制御できます
- 特定の文章に指定する
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/my_font" />
- Kotlinで指定する
textView.typeface = ResourcesCompat.getFont(this, R.font.my_font)
- アプリ全体へ適用する
<style name="AppTheme" parent="Theme.Material3.DayNight">
<item name="android:fontFamily">@font/my_font</item>
</style>
昔の方法(fontPath)
以前はfontPathを使用して適応する方法がありました。
フォントファイルを assets/fonts に配置します。
app/src/main/assets/fonts/my_font.ttf
- Kotlinで指定する
val typeface = Typeface.createFromAsset(assets, "fonts/my_font.ttf")
textView.typeface = typeface
- XMLで指定する。Calligraphyなどのライブラリも使用します。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:fontPath="fonts/my_font.ttf" />
特徴
- Android公式機能ではない
- Calligraphyなどの外部ライブラリが必要
- 保守されていないケースが多い
- 現在はほぼ使われない