安卓AlertDialog标题字体

7
I am trying to change the font of android.support.v7.app.AlertDialog title text. METHOD 1: 我正在尝试更改android.support.v7.app.AlertDialog标题文本的字体。
   TextView title = (TextView) dialog.findViewById(android.R.id.title); //returns null

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

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

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

谢谢。


你的上下文可能为空,请检查一下!请发布AlertDialog的完整代码。 - Piyush
4个回答

8
请使用这个。
TextView title = (TextView) dialog.findViewById(R.id.alertTitle);

没有自定义标题 :)

7

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

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

1

我已经看过他的解决方案。它类似于使用自定义布局。有没有办法获得默认标题 TextView? - quad
我认为没有办法获取默认的,但这个解决方案有什么问题呢?你可以从中设置标题,也可以更改字体。你还可以尝试一些第三方对话库,也许这是最后的选择。 - Sid

1
创建一个简单的TextView。
TextView tv;

把HTML中的

替换为


builder.setTitle("My Title");

带有。
builder.setCustomTitle(tv);

它不会抛出空指针异常吗? - Piyush
以上的TextView(tv)是您的小部件。因此,在使用它之前,您需要使用findViewById()方法找到它。 - Jayakrishnan Salim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接