crtn crtn - 2 months ago 26
Android Question

Android AlertDialog title font

I am trying to change the font of

android.support.v7.app.AlertDialog
title text.

METHOD 1 :

TextView title = (TextView) dialog.findViewById(android.R.id.title); //returns null


METHOD 2 :

final int titleId = context.getResources().getIdentifier("alertTitle", "id", "android");
TextView title = (TextView) dialog.findViewById(titleId); //Also returns null.


Is there any other way to get the title
TextView
?

Please note I do not want to use a custom layout.

Thanks.

Answer Source

I got it to work using this solution :

    final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);  

    Typeface tf = //get the typeface.
    CustomTFSpan tfSpan = new CustomTFSpan(tf);
    SpannableString spannableString = new SpannableString(title);
    spannableString.setSpan(tfSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    alertBuilder.setTitle(spannableString);

    AlertDialog dialog = alertBuilder.create();
    dialog.show();

CustomTFSpan

public class CustomTFSpan extends TypefaceSpan {

  private Typeface typeface;

  public CustomTFSpan(Typeface typeface) {
    super("");
    this.typeface = typeface;
  }

  @Override
  public void updateDrawState(TextPaint ds) {
    applyTypeFace(ds, typeface);
  }

  @Override
  public void updateMeasureState(TextPaint paint) {
    applyTypeFace(paint, typeface);
  }

  private static void applyTypeFace(Paint paint, Typeface tf) {
    paint.setTypeface(tf);
  }
}