In XML
android:textStyle
- normal
- bold
- italic
android:fontFamily
android:fontFamily="sans-serif" // roboto regular
android:fontFamily="sans-serif-light" // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed
android:fontFamily="sans-serif-black" // roboto black
android:fontFamily="sans-serif-thin" // roboto thin (android 4.2)
android:fontFamily="sans-serif-medium" // roboto medium (android 5.0)
可以把后面的字符串放到 fonts.xml
或 strings.xml
中,以便复用。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="font_family_light">sans-serif-light</string>
<string name="font_family_medium">sans-serif-medium</string>
<string name="font_family_regular">sans-serif</string>
<string name="font_family_condensed">sans-serif-condensed</string>
<string name="font_family_black">sans-serif-black</string>
<string name="font_family_thin">sans-serif-thin</string>
</resources>
Combination
除了单独使用外,textStyle
和 fontFamily
还能够组合使用
- Roboto regular
- Roboto italic
- Roboto bold
- Roboto bold italic
- Roboto-Light
- Roboto-Light italic
- Roboto-Thin
- Roboto-Thin italic
- Roboto-Condensed
- Roboto-Condensed italic
- Roboto-Condensed bold
- Roboto-Condensed bold italic
- Roboto-Black
- Roboto-Black italic
- Roboto-Medium
- Roboto-Medium italic
In Java
setTypeface
在 Java
文件中可以通过 setTypeface
来实现上述标签的效果
textView.setTypeface(typeface);
//Typeface.java
public class Typeface {
//.......
/** The default NORMAL typeface object */
public static final Typeface DEFAULT;
/**
* The default BOLD typeface object. Note: this may be not actually be
* bold, depending on what fonts are installed. Call getStyle() to know
* for sure.
*/
public static final Typeface DEFAULT_BOLD;
/** The NORMAL style of the default sans serif typeface. */
public static final Typeface SANS_SERIF;
/** The NORMAL style of the default serif typeface. */
public static final Typeface SERIF;
/** The NORMAL style of the default monospace typeface. */
public static final Typeface MONOSPACE;
//.......
}
创建 Typeface
#1
Typeface typeface = Typeface.create("sans-serif-medium",Typeface.NORMAL)
#2
//Android 4.1 (API Level 16) and Support Library 26 and higher
Typefeace typeface = ResourcesCompat.getFont(Context, R.font.YOUR_FONT)
#3
Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/mycustomfont.ttf");
setTextAppearance
<style name="styleA">
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">?android:attr/textColorPrimary</item>
</style>
<style name="styleB">
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
<item name="android:textColor">?android:attr/textColorTertiary</item>
</style>
if(condition){
textView.setTextAppearance(context,R.style.styleA);
}else{
textView.setTextAppearance(context,R.style.styleB);
}