如何将字符串中的某些单词更改为BOLD?

时间:2014-06-27 07:57:27

标签: android regex string

这是我在代码中使用json api从网上获取的字符串:

String content = "<strong><em>India is the world’s hub for child sex trafficking</em>
</strong></p>\n<p style=\"text-align: center;\"><strong><em>Nearly 40,000 children are
abducted every year… </em></strong></p>\n<p style=\"text-align: center;\"><strong<em>
Every8 minutes a girl child goes missing in India!</em></strong></p>\n<p><strong>Priti
Pathak</strong></p>\n<p>MEET Shivani Shivaji Roy, Senior Inspector, Crime Branch, Mumbai
Police, as she sets out to confront the mastermind behind the child trafficking mafia,"

在此字符串中,无论文本在

"<strong><em> TEXT </em></strong>"

我想把它显示出来。所以对于上面的字符串

<strong><em>India is the world’s hub for child sex trafficking</em></strong> 

将显示为 印度是全球儿童性交易的中心     。这应该发生在整个字符串中。这是我正在使用的代码:

 int startIndex = content.indexOf("<strong><em>")+13;  // 13 because <strong><em> has 13 characters

        String substring = content.substring(startIndex, startIndex+200);
         int subendIndex = substring.indexOf("</em></strong>");
         int endIndex = startIndex + subendIndex;

SpannableString s = new SpannableString(content);
s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), startIndex, endIndex, 0);
textview.setText(s, BufferType.SPANNABLE ); 

此代码正在运行,但它仅将粗体文本设置为强标记中的第一个文本,而不是其他文本。因为我只将粗体文本设置为第一个标记。

我应该如何获得所有&#34;强标签的startIndex,endIndex&#34;所以我可以设置

s.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), startIndex, endIndex, 0);

所有文本以及我必须设置范围的次数。

我虽然也使用正则表达式,但我不知道如何使用它获取索引。你能帮忙的话,我会很高兴。谢谢!

4 个答案:

答案 0 :(得分:3)

这是一种简单的方法

TextView TV = (TextView)findViewById(R.id.Tv);
            String  Title="I N <big>D</big> I A";
            TV.setText(Html.fromHtml(Title));

答案 1 :(得分:2)

更简单的方法是使用Html类:

s = Html.fromHtml(content);

有关详细信息,请参阅documentation

答案 2 :(得分:1)

如果你只想加粗一些字符串,那么我推荐使用Html.fromHtml。简短的样本:

String str = "<b> bold text</b> unbold one";
textView.setText(Html.fromHtml(str));

这是textview支持的list个html标签。

答案 3 :(得分:1)

在字符串中使用常规HTML标记,此文本使用粗体斜体,方法是使用内嵌标记,例如字符串文件。请参阅此链接 Hope this Link would be helpful for you!