通过Android中的应用程序类为TextView自定义字体



如何为整个应用程序维护自定义字体。而不是从Android中的资产加载文件。例如下面的

TextView tv =(TextView)findViewById(R.id.textview1);
Typeface type =Typeface.createfromAssets(this,"custom.ttf");
tv.setTypeface(type);

创建一个类似"CustomTextView"的新类这扩展了TextView。

默认情况下,将字体设置为此CustomTextView并使用您的CustomTextView在应用程序的其余部分。

您可以使用书法为应用程序定义自定义字体(https://github.com/chrisjenx/Calligraphy)

在您的build.gradle中添加依赖项:

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

添加字体

将自定义字体添加到assets/fonts/文件夹

安装,为整个应用程序设置默认字体

在#onCreate()方法中的Application类中,使用CalligraphyConfig定义默认字体。

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

注意:您不需要定义CalligraphyConfig,但库将不应用默认字体,并使用R.id.fontPath.的默认属性

在每个活动中:

在应用程序的每个Activity中都要使用新字体:

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

你可以走了!

最新更新