具有自定义字体的 AlertDialogPro

AlertDialogPro with custom Typeface

我正在尝试为使用 AlertDialogPro 构建的对话框设置自定义字体,但在尝试使用 dialog.getButton(int) 检索对话框按钮时出现 NPE。以及如何设置消息的字体和对话框的标题?

AlertDialogPro.Builder builder = new AlertDialogPro.Builder(this);
   builder.setMessage(getResources().getString(R.string.dialog_body))
   .setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
          // Do stuff
      }
});

AlertDialogPro dialog = builder.create();
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTypeface(customTf));
dialog.show();

日志:

03-02 16:30:22.982: E/AndroidRuntime(15596): 
java.lang.NullPointerException: Attempt to invoke virtual method 'void android
.widget.Button.setTypeface(android.graphics.Typeface)' on a null
object reference

调用此方法:

builder.setPositiveButton(int textId,final OnClickListener listener)

创建对话框之前

您只能在调用 dialog.show() 后访问对话框按钮(通过 dialog.getButton(DialogInterface.BUTTON_POSITIVE))。

通过做两件事修复了它:

  1. 将 getButton() 移到 dialog.show()
  2. 之后
  3. 使用 findViewById() 检索消息文本视图

代码:

AlertDialogPro.Builder builder = new AlertDialogPro.Builder(this);
   builder.setMessage(getResources().getString(R.string.dialog_body))
   .setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
          // Do stuff
      }
});

AlertDialogPro dialog = builder.create();
dialog.show();
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTypeface(customTf));
((TextView) dialog.findViewById(R.id.adp_message)).setTypeface(customTf);