如何在android中的alertDialog.setMessage()中显示带颜色的String变量

时间:2017-10-07 17:51:15

标签: android android-alertdialog fromhtml

我希望我的alertDialog看起来像这样 enter image description here

我的API是26,这是我目前为止的代码

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

正如您所看到的,我只是将9.00直接放在String中。 现在,我想制作一个名为estCost的字符串变量9.00,可以根据我的代码中的计算进行更改。

如何在alertDialog.setMessage()中显示“带颜色的字符串变量”estCost?

我尝试过以下代码

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

但它不起作用。请帮我 !感谢。

3 个答案:

答案 0 :(得分:0)

您需要使用连接运算符&#34; +&#34;

来连接值
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Guitar Store</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Guitar Store", "List", "Product", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "List", "Product")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    <li>@Html.Action("Summary", "Cart")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <br /><br /><br />
    <div class="row panel">
        <div id="categories" class="col-lg-3">
            @Html.Action("Menu", "Nav")
        </div>
        <div class="col-lg-7">@RenderBody()</div>
    </div>
</body>
</html>

答案 1 :(得分:0)

使用spannable text

Spannable myText = new SpannableString("are u sure.....");        
myText.setSpan(new ForegroundColorSpan(Color.RED),7,10,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
alertDialog.setMessage(myText);

答案 2 :(得分:0)

你需要连接字体,所以在字体标记之前和字体标记之后使用+。