【问题标题】:Android AlertDialog title fontAndroid AlertDialog 标题字体
【发布时间】:2015-12-01 09:44:25
【问题描述】:

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

方法一:

   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 的完整代码。

标签: android android-alertdialog


【解决方案1】:

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

自定义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);
  }
}

【讨论】:

    【解决方案2】:

    用这个

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

    没有任何自定义标题:)

    【讨论】:

      【解决方案3】:

      你的问题已经在这里回答了:Change Title Font Of Alert Dialog Box Android

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

      【讨论】:

      • 我已经看到了他的解决方案。它类似于使用自定义布局。有没有办法获取默认标题TextView?
      • 我不认为有任何方法可以获得默认值,但这个解决方案有什么问题。您可以从中设置标题,也可以更改字体。您也可以尝试一些第三方对话库,可能这是最后的选择。
      【解决方案4】:

      创建一个简单的TextView

      TextView tv;
      

      并替换

      builder.setTitle("My Title");
      

      builder.setCustomTitle(tv);
      

      【讨论】:

      • 不会抛出空指针异常吗?
      • 上面的 textview (tv) 是你的小部件。所以你需要在使用前使用 findViewById() 方法找到它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多