我有一个像这样的字符串:
String s="12 year old Manick is <b>three</b> times as old as his brother Rahul. How old will Manick be when he is twice as old as Rahul ?";
当我将此字符串设置为 TextView 时,输出如下:
我想要的是,输出是这样的:
12 岁的马尼克 (Manick) 的年龄是他弟弟拉胡尔 (Rahul) 的三倍。当马尼克的年龄是拉胡尔的两倍时,他有多大?
应该对原始字符串执行什么操作才能在 TextView 中获得所需的输出?
实际上,我的要求是提取 HTML 标记内的文本,将粗体格式应用于标记内的文本,并在显示在 TextView 中之前从字符串中删除标记。
提前致谢!
P.S.:该字符串来自 XML 文件,因此可能会有所不同!
最佳答案
您可以尝试在 strings.xml 中为 TextView 定义文本。然后,如果您从 html 设置,那么它可能会根据屏幕尺寸换行:
所以你可以尝试一下:
<string name="nice_html">
<![CDATA["12 year old Manick is <b>three</b> times as old as his brother Rahul. How old will Manick be when he is twice as old as Rahul ?";
]]></string>
然后,在您的代码中:
TextView foo = (TextView)findViewById(R.id.foo); foo.setText(Html.fromHtml(getString(R.string.nice_html)));
编辑:
只需将最后一个代码更改为
//string s already defined in the question
TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(s)));
关于java - 将 html 字符替换为 ""(空白)并将样式应用于其中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15739386/