运行时异常:找不到我尝试过的每种字体的字体 - Android

Runtime Exception: Font not found for every font i've tried - Android

我有一个自定义扩展 TextView 我在我的应用程序中使用自定义字体,但由于某种原因,我不断收到 运行-time 异常,程序找不到字体有问题。

我使用的目录格式是main > assets > fonts > Portrait-Light.ttf

我到处寻找解决方案,但他们似乎都在 SO 上四舍五入到相同的答案。

CustomFontTextView.java :

public class CustomFontTextView extends TextView {

    public CustomFontTextView(Context context) {
        super(context);
        applyCustomFont(context);
    }

    public CustomFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        applyCustomFont(context);
    }

    public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        applyCustomFont(context);
    }

    private void applyCustomFont(Context context) {
        Log.e("it gets here", "custom font");
        Typeface customFont = FontCache.getTypeface("Roboto-Italic.ttf", context);
        setTypeface(customFont);
    }
}

FontCache.java

class FontCache {

    private static HashMap<String, Typeface> fontCache = new HashMap<>();

    static Typeface getTypeface(String fontname, Context context) {
        Typeface typeface = fontCache.get(fontname);
        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), "fonts/" + fontname);
            } catch (Exception e) {
                Log.e("failed", e.getMessage());
            }
            fontCache.put(fontname, typeface);
        }
        return typeface;
    }
}

XML:

 <icn.premierandroid.misc.CustomFontTextView
            android:id="@+id/switch_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:textSize="14sp"
            android:textColor="@color/colorPrimary"
            android:gravity="center_horizontal"
            android:text="@string/are_you_over_18_years_old"/>

我已经尝试过使用不同的格式,例如 .otf 和不同的字体,例如 Roboto-Italic.ttf 和另一个来自 dafont.com 的随机字体 Sunset-Clouds.ttf 但我仍然明白错误信息,这是怎么回事?这应该工作。我什至更新了所有插件,例如 Gradle、Grade-Wrapper 分发和 Android gradle 插件以防万一。

我也试过单一的方法:

    AssetManager am = context. getApplicationContext(). getAssets();
    Typeface font = Typeface.createFromAsset(
    am, String.format(Locale.US, "fonts/%s", "portrait-light.ttf"));

我是不是漏掉了什么?

更新:

删除 catch 会显示此堆栈跟踪。

Process: icn.premierandroid, PID: 3829 java.lang.RuntimeException: Unable to start activity ComponentInfo{icn.premierandroid/icn.premierandroid.RegisterActivity}: android.view.InflateException: Binary XML file line #100: Error inflating class icn.premierandroid.misc.CustomFontTextView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767) .....

Caused by: android.view.InflateException: Binary XML file line #100: Error inflating class icn.premierandroid.misc.CustomFontTextView at android.view.LayoutInflater.createView(LayoutInflater.java:640) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750) at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)

.....

Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.newInstance(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:288) at android.view.LayoutInflater.createView(LayoutInflater.java:614)

....

Caused by: java.lang.RuntimeException: Font asset not found fonts/GleegooRegular.ttf at android.graphics.Typeface.createFromAsset(Typeface.java:272) at icn.premierandroid.misc.FontCache.getTypeface(FontCache.java:21) at icn.premierandroid.misc.CustomFontTextView.applyCustomFont(CustomFontTextView.java:28) at icn.premierandroid.misc.CustomFontTextView.(CustomFontTextView.java:18) at java.lang.reflect.Constructor.newInstance(Native Method) 

.....

更新 2:

好的,所以有一个奇怪的解决方法。显然 android 工作室不喜欢将 assets 文件夹直接添加到 app/src/main 内的 main 文件夹中。您需要先将其添加到 app/src/main/res 文件夹中,然后再将其移动到 main 文件夹中。不知道为什么会这样,但它解决了我的问题。

我们写这个 class 是为了我们的需要。它允许使用属性设置我们的自定义字体,如下所示:

app:customFont="Roboto-Medium.ttf"

希望你觉得有用:

public class TextViewFonted extends TextView {
    private static final String TAG = "TextViewFonted";

    public TextViewFonted(Context context) {
        super(context);
    }

    public TextViewFonted(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }

    public TextViewFonted(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewFonted);
        String customFont = a.getString(R.styleable.TextViewFonted_customFont);
        if (customFont == null) customFont = "Roboto-Regular.ttf";
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface tf = null;
        try {
            tf = Typeface.createFromAsset(ctx.getAssets(), asset);  
        } catch (Exception e) {
            Log.e(TAG, "Could not get typeface", e);
            return false;
        }

        setTypeface(tf);  
        setLineSpacing(getTextSize() * 0.3f, 0.75f);
        return true;
    }
}

并且为了能够使用这个自定义属性,您应该添加到您的 attrs.xml 下一个块(所以 R.styleable.TextViewFonted_customFont 会起作用):

 <declare-styleable name="TextViewFonted">
        <attr name="customFont" format="string"/>
 </declare-styleable>

在我们的例子中,我们将字体放在 assets 文件夹的根目录中,但您可以在方法 setCustomFont() 中更改此行为

更新

添加这个字体,比如我们使用

app:customFont="Comfortaa-Bold.ttf"

我认为真正的问题是你没有配置你的资产文件夹。如果有,它在项目视图中将如下所示:

或者在 Android 视图中像这样:

因此,您只需将此文件夹添加为 Studio 中的资产文件夹即可: 单击您的项目结构 window(或按 Alt+1),然后按 Alt + Insert 和 select Folder/Assets 文件夹。然后把你的字体放在那里。

OP 更新:

Okay, so there is a weird work-around for this. Apparently android studio doesn't like it when you add the assets folder straight into the main folder inside app/src/main. You need to add it into the app/src/main/res folder first and then move it to the main folder. Don't have a clue why it's like this but it solved my problem.

试试这个....

put .ttf fonts in app > assets > fonts > Roboto-Italic.ttf

然后在onCreate方法中,

Typeface Roboto = Typeface.createFromAsset(getAssets(),
            "fonts/Roboto-Italic.ttf");

并在文本视图中设置字体等

textview.setTypeface(Roboto);