androidandroid-alertdialogfromhtml

how to show a String variable with color in alertDialog.setMessage() in android


I want my alertDialog look like this enter image description here

My API is 26, and this is my code so far

alertDialog.setTitle("Warning");
alertDialog.setMessage(Html.fromHtml("Are you sure"+"\n"+"\n"+"<font color='#00bfff'><br><br><b>Est. Total Cost : $ 9.00 </b></font>",Build.VERSION.SDK_INT));

As you can see I just put 9.00 directly in the String. Right now, I want to make 9.00 a string variable called estCost, which can be changed based on the calculation in my code.

How can I display the "string variable with the color" estCost in the alertDialog.setMessage() ?

I have tried following code

String estCost = calculate(10)  //calculate method will return a double in string.
alertDialog.setTitle("Warning");
alertDialog.setMessage(Html.fromHtml("Are you sure"+"\n"+"\n"+"<font color='#00bfff'><br><br><b>Est. Total Cost : $ <var> estCost </var></b></font>",Build.VERSION.SDK_INT));

But it doesn't work. Please help me ! Thanks.


Solution

  • You need to concat the value using concatenation operator "+"

    alertDialog.setMessage(Html.fromHtml("Are you sure"+"\n"+"\n"+"<font color='#00bfff'><br><br><b>Est. Total Cost : $ <var>"+ estCost+" </var></b></font>",Build.VERSION.SDK_INT));