Android AlertDialog 标题字体

ckd*_*ckd 6 android android-alertdialog

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

方法一:

   TextView title = (TextView) dialog.findViewById(android.R.id.title); //returns null
Run Code Online (Sandbox Code Playgroud)

方法二:

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

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

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

谢谢。

ckd*_*ckd 6

我使用这个解决方案让它工作:

    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();
Run Code Online (Sandbox Code Playgroud)

自定义TFspan

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);
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

用这个

TextView title = (TextView) dialog.findViewById(R.id.alertTitle);
Run Code Online (Sandbox Code Playgroud)

没有任何自定义标题:)