Android AlertDialog title font

主宰稳场 提交于 2019-12-21 22:23:51

问题


I am trying to change the font of android.support.v7.app.AlertDialogtitle 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.


回答1:


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);
  }
}



回答2:


Use this one

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

Without any custom title :)




回答3:


Your question has already answer here : Change Title Font Of Alert Dialog Box Android

You can simply use a textview and set it as custom title like this : builder.setCustomTitle(tv2);




回答4:


Create a simple TextView

TextView tv;

And replace

builder.setTitle("My Title");

with

builder.setCustomTitle(tv);


来源:https://stackoverflow.com/questions/34017199/android-alertdialog-title-font

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!