Android AlertDialog标题字体

Android AlertDialog title font

我正在尝试更改 android.support.v7.app.AlertDialog标题文本的字体。

方法一:

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

方法二:

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

有没有其他方法获得标题TextView

请注意我不想使用自定义布局。

谢谢。

您的问题已经在这里得到解答:Change Title Font Of Alert Dialog Box Android

您可以简单地使用文本视图并将其设置为自定义标题,如下所示:builder.setCustomTitle(tv2);

创建一个简单的 TextView

TextView tv;

并替换

builder.setTitle("My Title");

builder.setCustomTitle(tv);

我使用这个 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);
  }
}

用这个

TextView title = (TextView) dialog.findViewById(R.id.alertTitle);

没有任何自定义标题:)