从 API 25 迁移到 26 时出现字体错误

Font error while migrating from API 25 to 26

目前我正在将我的项目从 targetSdkVersion 25 迁移到 26 这是我的 app.gradle:

android {
    compileSdkVersion 26
    buildToolsVersion "27.0.2"

    defaultConfig {
        minSdkVersion 17

        targetSdkVersion 26

        multiDexEnabled true

        versionCode versionMajor * 100000 + versionMinor * 1000 + versionPatch * 10 + versionHotfix
        versionName "${versionMajor}.${versionMinor}.${versionPatch}"
    }
}

但是在升级时我反复遇到这个错误:

String types not allowed (at 'font' with value 'Knockout-31').
Message{kind=ERROR, text=String types not allowed (at 'font' with value 'Knockout-31')., sources=[D:\Qdoba-Android\qdoba-android-app\app\build\intermediates\res\merged\internal\debug\values\values.xml:2466:21-32], original message=, tool name=Optional.of(AAPT)}

这是字体文件夹的片段:

请帮忙。

根据 Android 文档 link

Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. You can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in your R file and are automatically available in Android Studio. You can access the font resources with the help of a new resource type, font. For example, to access a font resource, use @font/myfont, or R.font.myfont.

因此您必须将所有字体移动到 res 中的字体文件夹中。 如果找不到字体目录,请在 res 目录中创建一个新的 'font' 目录。

在您的视图中使用如下字体,

android:fontFamily="@font/Knockout-31"

不使用属性 android:fontFamily = "..." 的另一种使用自定义字体系列的方法

  1. 对于文本浏览量

    public class customFont extends android.support.v7.widget.AppCompatTextView{
    
    public customFont(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    
    public customFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public customFont(Context context) {
        super(context);
        init();
    }
    
    public void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "Knockout-31.otf");
        setTypeface(tf ,1);
    
    }
    }
    

您使用自定义字体的文本视图

    <example.com.example.customFont
         android:id="@+id/textView"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Text View" />

谢谢

解决方法:更新gradle插件3.0以上