Search code examples
androidalertdialogpro

AlertDialogPro with custom Typeface


I'm trying to set a custom typeface to a dialog built using AlertDialogPro but get a NPE when trying to retrieve the dialog Button using dialog.getButton(int). And how can I set the typeface for the message and title of the dialog?

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

Log:

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

Solution

  • Fixed it by doing two things:

    1. Moved the getButton() to after dialog.show()
    2. Used findViewById() to retrieve the message textview

    Code:

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