【问题标题】:androidx custom fonts on lower api's较低 apis 上的 android 自定义字体
【发布时间】:2018-10-15 19:34:31
【问题描述】:

我在我的 Kotlin 应用程序中使用 AndroidX,并且一直在尝试添加自定义字体。我在 res/font 中有 .ttf 文件和 2 个字体系列(v26 和普通)的文件夹。 v26 文件包含 android: 前缀,而另一个文件包含 app: 前缀。

我还在 gradle 中添加了 appcompat 和 legacy-support 实现,但不知何故,我仍然无法让字体在 Android 6.0 上正确显示(适用于较新的设备)。我将 AppTheme 中的字体系列设置为:

    <item name="fontFamily">@font/avalon</item>

我不知道我还能尝试什么。有人遇到过同样的问题吗?

【问题讨论】:

    标签: android xml fonts


    【解决方案1】:

    我认为您不能将 fontFamily 用于旧 API 中的自定义字体。

    但是,您可以创建自己的 TextView(扩展默认的)并设置自定义字体:

    public class MyTextView extends TextView {
    
    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public MyTextView(Context context) {
        super(context);
        init();
    }
    
    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/custom.ttf");
            setTypeface(tf);
        }
    }
    

    }

    或者像这样设置字体:

    Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/custom.ttf");
    myTextView.setTypeface(typeface);
    

    【讨论】:

    • 有没有办法用代码全局设置字体?
    • 根据我的经验,您应该使用自定义字体创建自定义组件 - 自定义 editText、textView 等。此外,您可以使用自定义属性从 XML 设置自定义字体,因此您可以指定字体并在自定义 TextView 和 setTypeface。
    • 我有自定义字体的组件的自定义样式,但它仍然只适用于较新的 api,尽管使用了 app compat。但我现在会尝试自定义元素类。
    • 您使用哪个版本的 appCompat?尝试实现 'com.android.support:appcompat-v7:26.1.0'
    • implementation 'androidx.appcompat:appcompat:1.0.0' 我正在使用androidx appcompat(因为我在整个应用程序中都使用了android x)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 2018-06-08
    • 2016-08-07
    • 2011-11-14
    • 1970-01-01
    • 2011-04-12
    • 2015-12-29
    相关资源
    最近更新 更多