Search code examples
javaandroidandroid-alertdialogandroid-fonts

How do I make my AlertDialog display its text in monospace font?


Here's where I display an AlertDialog:

  public void showCenteredInfoDialog(TextView _title, TextView _message)  {
    _title.setGravity(Gravity.CENTER);
    this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setPositiveButton("OK", null);
    builder.setCustomTitle(_title);
    builder.setMessage(_message.getText());
    AlertDialog dialog= builder.show();

    TextView messageView = (TextView) dialog.findViewById(android.R.id.message);
    messageView.setGravity(Gravity.CENTER);
  }

I'd like the font to be monospace.

Do I need to modify an xml file or can Java alone handle this? (If Java CAN handle it, it would probably take API 21, yes?)

I wonder if adding messageView.setFontFeatureSettings("..."); or messageView.setTypeface(...) with some way to refer to monospace would work. I can't find syntax for the String argument for setFontFeatureSettings.


Solution

  • This should work for your problem. Add it in the TextView part:

    TextView messageView = (TextView) dialog.findViewById(android.R.id.message);
    messageView.setTypeface(Typeface.MONOSPACE);
    messageView.setGravity(Gravity.CENTER);
    

    Also is possible to change the font in XML, but i think this it's more confortable.

    Hope this will help you! :)