Stack Overflow archive
17 score

Change title font of Alert Dialog box

score
17
question views
29.5K
license
CC BY-SA 3.0

No answers provide a way to change the title typeface of an AlertDialog. Here is what I have done:

Create the below class:

java
public static class TypefaceSpan extends MetricAffectingSpan {

  private final Typeface typeface;

  public TypefaceSpan(Typeface typeface) {
    this.typeface = typeface;
  }

  @Override public void updateDrawState(TextPaint tp) {
    tp.setTypeface(typeface);
    tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
  }

  @Override public void updateMeasureState(TextPaint p) {
    p.setTypeface(typeface);
    p.setFlags(p.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
  }

}

Add the following utility method:

java
/**
 * <p>Return spannable string with applied typeface in certain style</p>
 *
 * http://stackoverflow.com/questions/8607707/how-to-set-a-custom-font-in-the-actionbar-title
 *
 * @param typeface
 *     The typeface to set to the {@link SpannableString}
 * @param string
 *     the string to place in the span
 * @return SpannableString that can be used in TextView.setText() method
 */
public static SpannableString typeface(Typeface typeface, CharSequence string) {
  SpannableString s = new SpannableString(string);
  s.setSpan(new TypefaceSpan(typeface), 0, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  return s;
}

Finally, set the typeface when creating your AlertDialog:

java
Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/your_font.ttf");
new AlertDialog.Builder(getActivity())
    .setTitle(FontUtils.typeface(typeface, "The title"))
    /* .. */
    .create();

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.