1

I have a AlertDialog that has multiple lines of text. I am looking to have a different color for each line of text. Any ideas on how one would go about this? Is it possible to set a span foreground color to a string variable?

API 30

enter image description here

    // Create Material Dialog
    MaterialAlertDialogBuilder dialogBuilder = new MaterialAlertDialogBuilder(MainActivity.this, R.style.AlertDialogTheme);
    dialogBuilder.setTitle(getString(R.string.alert_dialog_title));
    SpannableString string = new SpannableString(
            "Text: " + variable1 +
            "\n\nText: " + variable2);
    string.setSpan(new ForegroundColorSpan(Color.RED), 0, string.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
    dialogBuilder.setMessage(string);
    dialogBuilder.show();
Pie
  • 856
  • 4
  • 12
  • 33

1 Answers1

1

As mentioned by @Gabe Sechan, you can use ForegroundColorSpan to color a segment of the text which goes into the MaterialAlertDialog,

val materialAlertDialogBuilder = MaterialAlertDialogBuilder( this )
val message = SpannableString( "Hello World" ).apply {
    setSpan( ForegroundColorSpan( Color.BLUE ) , 6 , 11 , SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE )
}
val dialog = materialAlertDialogBuilder.run {
    setTitle( "Some Title" )
    setMessage( message )
    create()
}
dialog.show()

You may also refer to this discussion.

The output ( on API level 28 ): enter image description here

Shubham Panchal
  • 4,061
  • 2
  • 11
  • 36
  • thanks for the answer. Is it possible to set the color to a string variable, and then add that variable plus other variables to the setMessage parameter?

    var1 = var1.setSpan(new ForegroundColorSpan(Color.RED), 0, var1.length(),
    SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
    string = var1 + var2;
    .setMessage(string);
    – Pie Mar 01 '22 at 18:49