当前位置: 首页 > 工具软件 > Calligraphy > 使用案例 >

简单改字体之Calligraphy

屈畅
2023-12-01

app中替换字体,两种单位,页面和单个view

使用Calligraphy,简洁又方便

1、页面替换

(1)导入依赖

dependencies {
    compile 'uk.co.chrisjenx:calligraphy:2.3.0'
}

(2)全局初始化(注意:只有需要在activity里使用才进行设置,单个view可以直接在布局里修改,不需要这一步

//在application中加入
@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                            .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()
            );
    //....
}

(3)给对应修改的activity里替换context

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

2、单个view

(1)导入依赖

dependencies {
    compile 'uk.co.chrisjenx:calligraphy:2.3.0'
}

(2)直接在布局中添加字体路径(不需要初始化

<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    fontPath="fonts/Roboto-Bold.ttf"/>
<!--
需要在parentview中加入
xmlns:tools=" http://schemas.android.com/tools"
tools:ignore="MissingPrefix"
-->

(3)或者对TextAppearance、Styles、Theme进行设置(没试过,官方copy下)

TextAppearance

<style name="TextAppearance.FontPath" parent="android:TextAppearance">
    <!-- Custom Attr-->
    <item name="fontPath">fonts/RobotoCondensed-Regular.ttf</item>
</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>

小记:使用OTF类型的字体失败,能识别TTF

 类似资料: