【问题标题】:Custom font for TextView through Application Class in Android [duplicate]通过Android中的应用程序类为TextView自定义字体[重复]
【发布时间】:2016-04-18 15:03:51
【问题描述】:

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

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

【问题讨论】:

  • Google 搜索在您所在的位置不起作用?我发现了几个使用以下搜索词的骗子:自定义字体应用程序 android。我想知道你为什么不这样做......哦,好吧。
  • 请确保您只实例化一次Typeface...创建Typeface 需要时间。

标签: android


【解决方案1】:

创建一个像“CustomTextView”这样的新类 它扩展了 TextView。

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

【讨论】:

    【解决方案2】:

    您可以使用 Calligraphy (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));
    }
    

    你可以走了!

    【讨论】:

    • 我做了以上步骤。默认字体替换成功,但设备上的新字体没有应用粗体、斜体等样式。
    • 它正在处理我的片段和活动,但不适用于我以编程方式为自定义对话框上的网格视图创建的文本视图
    猜你喜欢
    • 2014-06-14
    • 1970-01-01
    • 2014-04-22
    • 2012-08-30
    • 2011-12-10
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多