创建一个
SpannableString
对象,并从资产中传递字体路径。请查看下面的工作情况。
SpannableString toolbarTitle = new SpannableString(getActionBar().getTitle());
String toolbarFont = getResources().getString(R.string.circular_bold);
CustomTypefaceSpan toolbarTypefaceSpan = new CustomTypefaceSpan(toolbarFont, this);
toolbarTitle.setSpan(toolbarTypefaceSpan, 0, toolbarTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
getActionBar().setTitle(toolbarTitle);
这里,
R.string.circular_bold
是什么。
<string name="circular_bold">font/CircularStd-Bold.ttf</string>
字体在下面图片中显示的
Asset/font
文件夹中。
以下
CustomFontHelper
类有助于将
Typeface
设置到文本元素中-
public class CustomFontHelper {
public static void setCustomFont(Paint paint, String font, Context context) {
if (font == null) {
return;
}
Typeface typeface = FontCache.get(font, context);
if (typeface != null) {
paint.setTypeface(typeface);
}
}
}
CustomTypefaceSpan
类是实际应用字体到文本元素的类。
public class CustomTypefaceSpan extends TypefaceSpan {
private String font;
private Context context;
public CustomTypefaceSpan(@NonNull String font, @NonNull Context context) {
super("");
this.font = font;
this.context = context;
}
@Override
public void updateDrawState(TextPaint ds) {
CustomFontHelper.setCustomFont(ds, font, context);
}
@Override
public void updateMeasureState(TextPaint paint) {
CustomFontHelper.setCustomFont(paint, font, context);
}
}
FontCache
类用于缓存字体,因此可以重复使用相同的字体。
public class FontCache {
private static Hashtable<String, Typeface> fontCache = new Hashtable<>();
public static Typeface get(String name, Context context) {
Typeface tf = fontCache.get(name);
if (tf == null) {
try {
tf = Typeface.createFromAsset(context.getAssets(), name);
} catch (Exception e) {
return null;
}
fontCache.put(name, tf);
}
return tf;
}
}
Toolbar
,那么我的答案是最好的答案,我可以保证这一点。因为即使我自己也在使用Toolbar
,只需使用toolbar.getTitle()
来提供标题。我不知道为什么它被评为负面,但我确信它会对你有所帮助。 - Jimit Patel