Android中通过应用程序类为TextView定制字体

Android中通过应用程序类为TextView定制字体,android,Android,如何为整个应用程序维护自定义字体。而不是从Android中的资产加载文件。例如,如下所示 TextView tv =(TextView)findViewById(R.id.textview1); Typeface type =Typeface.createfromAssets(this,"custom.ttf"); tv.setTypeface(type); 创建一个新类,如“CustomTextView” 它扩展了TextView 默认情况下,将字体设置为此CustomTextView并使用

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

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

创建一个新类,如“CustomTextView” 它扩展了TextView

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

您可以使用书法()为应用程序定义自定义字体

在build.gradle中添加依赖项: 添加字体 将自定义字体添加到
资产/font/
文件夹

安装,为整个应用程序设置默认字体 在应用程序类的#onCreate()方法中,使用CalligraphyConfig定义默认字体

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

在每项活动中: 在您希望使用新字体的应用程序的每个
活动中执行此操作:

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

你可以走了

谷歌搜索在你的位置不起作用?我用以下搜索词找到了几个副本:自定义字体应用程序android。我想知道你为什么不这么做。。。哦,好吧。请确保只实例化一次
字体。。。创建
字体需要时间。我完成了上述步骤。默认字体已成功替换,但粗体、斜体等样式未应用于设备上的新字体。它正在处理我的片段和活动,但不处理我正在为自定义对话框上的gridview以编程方式创建的textview
@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                            .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()
            );
    //....
}
@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}