简体   繁体   English

Android格式化xml字符串丢失其html标记

[英]Android formatting xml string loses its html tags

I have a xml string below that contains html tags such as Bold and a hyperlink href. 我在下面有一个xml字符串,其中包含html标签,如Bold和超链接href。

<string name"example"><b>%1$s</b> has been added to your clipboard  and is valid until  <b>%2$s</b><a href="http://www.google.com">Please see our +T\'s and C\'s+ </a>   </string>

when i format the string to dynamically add some values it removes the bolded text and href I defined. 当我格式化字符串以动态添加一些值时,它会删除我定义的粗体文本和href。

code below: 代码如下:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yy");
Date date = new Date(text.getValidTo()); 
String text = String.format(getString(R.string_dialog_text), text.getCode(), simpleDateFormat.format(date), "£30");

I then apply it to a alert dialog 然后我将其应用于警报对话框

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setNeutralButton(R.string.ok, onClickListener);
builder.setTitle(title);
builder.setMessage(text);

this worked fine if i dont format the text and directly use the string resource 如果我不格式化文本并直接使用字符串资源,这工作正常

use Html.fromHtml 使用Html.fromHtml

builder.setMessage(Html.fromHtml(text));

when you apply the formatting, the CharSequence is converted back to String , and you need the Spannable with the html information. 应用格式时, CharSequence将转换回String ,并且您需要具有html信息的Spannable

From the doc: 来自doc:

Sometimes you may want to create a styled text resource that is also used as a format string. 有时您可能希望创建一个样式化的文本资源,该资源也用作格式字符串。 Normally, this won't work because the String.format(String, Object...) method will strip all the style information from the string. 通常,这不起作用,因为String.format(String,Object ...)方法将从字符串中删除所有样式信息。 The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place. 解决这个问题的方法是使用转义实体编写HTML标记,然后在格式化后使用fromHtml(String)恢复这些实体。

try with &lt;b> in place of <b> and with &lt;/b> in place </b> 尝试使用&lt;b>代替<b>并使用&lt;/b>到位</b>

Suppose that you want this 假设你想要这个

<resources>
<string name="our_string_key">
    <B>Title</B> <I>Italic</I><BR/>
    Content
</string>
</resources>

Then in that case you yse it as 那么在那种情况下你就是这样的

textview.setText(Html.fromHtml(R.String.our_string_key));

If in case you are getting errror then you can use it as 如果您遇到错误,那么您可以将其用作

   textview.setText(Html.fromHtml(getResources().getString(R.String.our_string_key)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM