I am trying to use Custom Typeface Span in my application but it doesn't working. Here is my code
Typeface font3 = Typeface.createFromAsset(context.getAssets(), "fontawesome-webfont.ttf");
SpannableStringBuilder SS = new SpannableStringBuilder("");
SS.setSpan(new CustomTypefaceSpan("", font3), 0, 8,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
textView.setText(SS);
Here I am trying to use Font-Awesome in Custom Typeface Span.
You can create a Custom TypefaceSpan and then you can use it anywhere to apply font style in any place. Create a class TypefaceSpan as mentioned below.
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 android.text.Spannable}.
*/
public TypefaceSpan(Context context, String typefaceName) {
mTypeface = sTypefaceCache.get(typefaceName);
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getApplicationContext()
.getAssets(), typefaceName);//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);
tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
and then you can use this class for applying font styles. Example--
actionBar=getSupportActionBar();
SpannableString s = new SpannableString("Hostel-16");
s.setSpan(new com.example.suraj.hostel16.TypefaceSpan(getApplicationContext(),"georgia.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
actionBar.setTitle(s);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.