如何在CollapsingToolbarLayout中更改工具栏标题的字体?

时间:2016-04-07 22:35:49

标签: android fonts toolbar android-collapsingtoolbarlayout

我一直在尝试更改其样式的大量试验和错误,但我仍然无法获得工具栏标题的字体更改(我也使用书法库)并且不确定工具栏标题的属性是在工具栏上还是在CollapsingToolbarLayout上。 任何帮助将不胜感激,谢谢!

enter image description here

1 个答案:

答案 0 :(得分:1)

你可以使用自定义的TypefaceSpan类并在你的Activity中像这样应用它,在这种情况下我想使用Arial:

SpannableString s = new SpannableString("CANTEEN");
s.setSpan(new TypefaceSpan(this, "Arial.otf"), 0, s.length(),
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

// Update the action bar title with the TypefaceSpan instance
ActionBar actionBar = getActionBar();
actionBar.setTitle(s);

您需要复制此类并将其保存在应用程序中,并将字体文件放在assets / fonts目录中。 (如本教程中所述:http://www.viralandroid.com/2016/01/how-to-use-custom-fonts-in-android-application.html) 它会将文件加载到内存中,并在具有该字体类型的实例中使用它。

/**
 * Style a {@link Spannable} with a custom {@link Typeface}.
 * 
 * @author Tristan Waddington
 */
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 Spannable}.
     */
    public TypefaceSpan(Context context, String typefaceName) {
        mTypeface = sTypefaceCache.get(typefaceName);

        if (mTypeface == null) {
            mTypeface = Typeface.createFromAsset(context.getApplicationContext()
                    .getAssets(), String.format("/%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);
    }
}

如果你想使用android的默认字体之一,你只有三个: 1正常(Droid Sans), 2 serif(Droid Serif), 3 monospace(Droid Sans Mono)。

希望它有所帮助!