Android - Set More Than One Color For Alert Dialog Text

Viewed 82

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

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

Related