前言
Android系统默认字体支持四种字体,分别为:
1,noraml (普通字体,系统默认使用的字体),
2,sans(非衬线字体)
3,serif (衬线字体)
4,monospace(等宽字体)
我们可以通过TextView 的 typeface 属性来指定使用哪种字体,如果不指定,系统默认使用 “Sans” 作为文本显示的字体。但这三种字体只支持英文,也就是说只要你显示的文字是中文,无论你选择这三种字体中的哪一种,显示效果都是一样的。
传统的设置第三方字体的方式
首先将下载的第三方 .ttf 字体文件放置在assets/目录下,以后使用过程中都将以此路径作为相对路径。当然你也可以在此路径下创建子目录,例如"fonts/"作为存放字体文件的目录,在布局文件中可以直接使用,如下:
然后在java代码中设置:
TextView txtView = (TextView) findViewById(R.id.txt_helvetica);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf");
txtView.setTypeface(typeface);
使用Calligraphy高效加载字体包
Calligraphy这个库的出现是为了更优雅的方式来解决替换字体时的耦合和性能问题的,GitHub地址:https://github.com/chrisjenx/Calligraphy ,使用步骤如下:
1,添加依赖
compile 'uk.co.chrisjenx:calligraphy:2.3.0'
2,添加第三方字体
将字体文件保存在assets/fonts/目录下
3,在Application的 onCreate 方法中初始化字体配置,如果不设置的话就不会生效
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Helvetica.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
}
}
4,在BaseActivity中重写attachBaseContext方法
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
5,在xml中独立设置单个View的自定义字体
<TextView
android:id="@+id/txt_helvetica"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lorem ipsum"
android:textSize="20dp"
android:textColor="#000000"
android:layout_margin="5dp"
fontPath="fonts/Helvetica.ttf"
tools:ignore="MissingPrefix"/>
如果fontPath="fonts/Helvetica.ttf"报错,在View上添加 tools:ignore="MissingPrefix”即可。
Calligraphy功能十分强大,从上面的说明中我们可以发现不仅支持简单的TextView,还支持继承于TextView的一些View,比如Button,EditText,CheckBox之类,还支持有setTypeFace()的自定义view。而且除了从View层面支持外,还包括从style,xml来进行个性化设置字体。
在TextAppearance中自定义字体
在res/values/styles.xml中添加风格:
<style name="TextAppearance.FontPath" parent="android:TextAppearance">
<!-- Custom Attr-->
<item name="fontPath">fonts/RobotoCondensed-Regular.ttf</item>
</style>
布局里直接使用style:
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.FontPath"/>
在styles中自定义字体
<style name="TextViewCustomFont">
<item name="fontPath">fonts/RobotoCondensed-Regular.ttf</item>
</style>
在主题theme中自定义字体
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>
</style>
<style name="AppTheme.Widget"/>
<style name="AppTheme.Widget.TextView" parent="android:Widget.Holo.Light.TextView">
<item name="fontPath">fonts/Roboto-ThinItalic.ttf</item>
</style>
优先级比较
View > Style > TextAppearance > Theme > Default