Calligraphy是android自定义字体库
添加依赖
DownloadfromMavenCentral(.jar)
OR
Java
dependencies{
compile'uk.co.chrisjenx:calligraphy:1.2.0'
}
123
dependencies{compile'uk.co.chrisjenx:calligraphy:1.2.0'}
使用
字体
把你的所有的自定义字体都添加到assets/fonts目录下,所有的字体引用的都是这个目录
自定义属性
我们没有在Jar包中打包R.attr,所以你需要自己添加你自己的Attr,下面是一个例子res/values/attrs.xml
Java
1234
配置
在Application类中,使用CalligraphyConfig定义你默认的字体,不幸的是Activity#onCreate(Bundle)在Activity#attachBaseContext(Context)之后调用,所以这个配置文件要在之前定义
Java
protectedvoidonCreate(){
super.onCreate();
CalligraphyConfig.initDefault("fonts/Roboto-Regular.ttf",R.attr.fontPath);
//....
}
12345
protectedvoidonCreate(){super.onCreate();CalligraphyConfig.initDefault("fonts/Roboto-Regular.ttf",R.attr.fontPath);//....}
注入到Context
Java
@Override
protectedvoidattachBaseContext(ContextnewBase){
super.attachBaseContext(newCalligraphyContextWrapper(newBase));
}
1234
@OverrideprotectedvoidattachBaseContext(ContextnewBase){super.attachBaseContext(newCalligraphyContextWrapper(newBase));}
给TextView自定义字体
Java
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fontPath="fonts/Roboto-Bold.ttf"/>
12345
在TextAppearance中自定义字体
Java
fonts/RobotoCondensed-Regular.ttf
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="@style/TextAppearance.FontPath"/>
123456789
在styles中自定义字体
Java
fonts/RobotoCondensed-Regular.ttf
123
CustomfontdefinedinTheme
Java
@style/AppTheme.Widget.TextView
fonts/Roboto-ThinItalic.ttf
开源地址:/chrisjenx/Calligraphy
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!