簡體   English   中英

Android應用程序和ActionBar中的自定義字體

[英]Custom font in Android app and ActionBar

我整個下午都在為自己的Android應用程序實現自定義字體而煩惱。 首先,我在導航抽屜中使用自定義字體時遇到了麻煩。 這似乎不起作用。 因此,我決定嘗試使用Actionbar標題,但是遇到了同樣的問題。

我找到了該網站http://www.tristanwaddington.com/2013/03/styling-the-android-action-bar-with-a-custom-font/,並決定嘗試一下。

我使用以下代碼創建了一個自定義Java文件:

package vimen.vimenlogin;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;
import android.util.LruCache;

public class TypefaceSpan extends MetricAffectingSpan {
    /** An <code>LruCache</code> for previously loaded typefaces. */
    private static LruCache<String, Typeface> sTypefaceCache =
    new LruCache<String, Typeface>(12);

    private Typeface mTypeface;

    /**
     * Load the {@link Typeface} and apply to a {@link}.
     */
    public TypefaceSpan(Context context, String typefaceName) {
        mTypeface = sTypefaceCache.get(typefaceName);

        if (mTypeface == null) {
            mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                .getAssets(), String.format("fonts/%s", typefaceName));

            // Cache the loaded Typeface
            sTypefaceCache.put(typefaceName, mTypeface);
        }
    }

    @Override
    public void updateMeasureState(TextPaint p) {
        p.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }

    @Override
    public void updateDrawState(TextPaint tp) {
        tp.setTypeface(mTypeface);

        // Note: This flag is required for proper typeface rendering
        tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
    }
}

除此之外,我將方法放在main.java文件中:

public void restoreActionBar()
{
    actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);

    SpannableString s = new SpannableString("testing");
    s.setSpan(new TypefaceSpan(this, "fonts/Raleway-Bold.ttf"), 0, s.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    // Update the action bar title with the TypefaceSpan instance
    actionBar.setTitle(s);
    //actionBar.setTitle(mTitle);
}

但是,出現此錯誤的Caused by: java.lang.RuntimeException: native typeface cannot be made與崩潰的應用程序結合使用。

TypefaceSpan不采用字體路徑。 它僅適用於內置字體系列。 從代碼片段站立時無法分辨它們是您使用的是TypefaceSpan還是內置的TypefaceSpan

(專業提示:為您使用與TypefaceSpan不同的類名)

該錯誤消息通常表示Android找不到字體文件或由於某種原因無法解釋它。 給定您的代碼,您的字體文件將需要為:

assets/fonts/fonts/Raleway-Bold.ttf

在你的項目,你有fonts/無論是在你的TypefaceSpan ,在你使用的是的TypefaceSpan 如果字體文件不存在,請移動它或修正代碼以引用其實際位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM