我整个下午都在为自己的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
。如果字体文件不存在,请移动它或修正您的代码以引用其实际位置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句