Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can do this using a custom <code>TypefaceSpan</code> class. It's superior to the <code>customView</code> approach indicated above because it doesn't break when using other Action Bar elements like expanding action views.</p> <p>The use of such a class would look something like this:</p> <pre><code>SpannableString s = new SpannableString("My Title"); s.setSpan(new TypefaceSpan(this, "MyTypeface.otf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // Update the action bar title with the TypefaceSpan instance ActionBar actionBar = getActionBar(); actionBar.setTitle(s); </code></pre> <p>The custom <code>TypefaceSpan</code> class is passed your Activity context and the name of a typeface in your <code>assets/fonts</code> directory. It loads the file and caches a new <code>Typeface</code> instance in memory. The complete implementation of <code>TypefaceSpan</code> is surprisingly simple:</p> <pre><code>/** * Style a {@link Spannable} with a custom {@link Typeface}. * * @author Tristan Waddington */ public class TypefaceSpan extends MetricAffectingSpan { /** An &lt;code&gt;LruCache&lt;/code&gt; for previously loaded typefaces. */ private static LruCache&lt;String, Typeface&gt; sTypefaceCache = new LruCache&lt;String, Typeface&gt;(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("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); } } </code></pre> <p>Simply copy the above class into your project and implement it in your activity's <code>onCreate</code> method as shown above.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload