Table of contents
1. Create an instance of loading fonts
1. Import the ttf file under res/font
foreword
The product tells you to use cool fonts when designing your UI. Because Android is not like a web project that can use the browser's native fonts, Android only has those fonts.
Two methods can be used:
-
android:typeface="serif"
-
android:fontFamily="@font/xxxx"
The typeface value is as follows
The fontFamily values are as follows
sans serif
sans-serif-condensed
sans-serif-smallcaps
serif
serif-monospace
minivan
casual
cursive
fontFamily priority is greater than typeface priority
You can check the Android common font library below
Android comes with font library https://blog.csdn.net/weixin_41620505/article/details/114673516
①Use the typeface method
1. Create an instance of loading fonts
The reflection method used
import android.content.Context
import android.graphics.Typeface
object FontsOverride {
/**
*staticTypefaceFieldName :最好是 normal、sans、serif、monospace其中一个
*/
fun setDefaultFont(context: Context, staticTypefaceFieldName: String, fontAssetName: String?) {
val regular = Typeface.createFromAsset(context.assets, fontAssetName)
replaceFont(staticTypefaceFieldName, regular)
}
internal fun replaceFont(staticTypefaceFieldName: String, newTypeface: Typeface?) {
try {
val staticField = Typeface::class.java.getDeclaredField(staticTypefaceFieldName)
staticField.isAccessible = true
staticField[null] = newTypeface
} catch (e: NoSuchFieldException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
}
}
}
2. Use steps
1. Load fonts in Application
Put the font ttf file in the assets/fonts directory, without this directory, create it manually
//staticTypefaceFieldName :最好是 normal、sans、serif、monospace其中一个
FontsOverride.setDefaultFont(this, "SERIF", "fonts/pangmenzhengdaobiaoti.ttf")
2. Use in xml
The code is as follows (example):
<TextView
android:id="@+id/newHomeLoction"
android:textColor="@color/white"
android:textSize="26sp"
android:typeface="serif"
app:layout_constraintStart_toStartOf="@+id/newHomeLeaveTitle"
app:layout_constraintTop_toBottomOf="@+id/newHomeLeaveTitle" />
② Use the fontFamily method
1. Import the ttf file under res/font
As shown below:
2. Use in xml
<TextView
android:id="@+id/newHomeLoction"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="bottom|end"
android:includeFontPadding="false"
android:paddingBottom="28dp"
android:fontFamily="@font/pangiaoti"
android:text="字体水水水水" />
Summarize
Using typeface does not require every TextView to be written, because there is a default font style (monospace)
Using the fontFamily method requires each TextView to be written once
used in xml layout
1:
android:typeface2:
android:fontFamilyMake a distinction