干货:直接参考官方demo:
快速集成步骤:
1、添加依赖:
2.导入字体文件:
如:E:\yg\Desktop\weekDay\WeekDay\app\src\main\assets\fonts\STLITI.TTF
3.拷贝官方DemoCalligraphySample中文件:
CustomViewWithTypefaceSupport.class
TextField.class
4.配置:
1)如果想给整个App设置默认自定义字体,先这么干,否则可跳过:
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
//给应用整体设置,可以不设置,仅仅在个别Activity中使用,重写attachBaseContext方法
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Roboto-ThinItalic.ttf")//如果没有这种字体,则使用默认字体,不会崩溃
// .setDefaultFontPath("fonts/STLITI.TTF")
.setFontAttrId(R.attr.fontPath)
.addCustomViewWithSetTypeface(CustomViewWithTypefaceSupport.class)
.addCustomStyle(TextField.class, R.attr.textFieldStyle)
.build()
);
}
}
2)如果只需要给某个控件,如TextView设置字体,这么干:
/**
* Activity中,重写下面方法,写到Base页面中较好
* @param newBase
*/
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
3)布局文件中,这么干:
3.1)
xmlns:tools="/tools"
tools:ignore="MissingPrefix"
3.2)
android:id="@+id/selectedDay1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginBottom="10dp"
android:background="@drawable/selector_btn"
android:text="查询"
android:gravity="center"
fontPath="fonts/STLITI.TTF"
android:textSize="18sp"
android:textColor="@color/textColor" />
结束。
查询按钮文字已改变: