突出显示TextView中可能包含HTML标记的文本

时间:2013-06-02 06:58:09

标签: java android regex textview highlight

我想制作关于正则表达式的应用程序。用户输入正则表达式和测试文本,我想突出显示与正则表达式匹配的测试文本中的所有内容。现在我做了这样的事情:

// txaTestText is an EditText
Editable testText = txaTestText.getText(); 

// pattern is a java.util.regex.Pattern input by user
Matcher matcher = pattern.matcher(testText);

// txaFindResult is a TextView
txaFindResult.setText(Html.fromHtml(matcher
        .replaceAll("<font color=\"red\">$0</font>")));

问题是用户可能会输入一些包含HTML标签的字符串作为测试文本。例如:

  • regex = o
  • 测试文字= Hello<br>world
  • 期望结果= Hello<br>world (由于StackOverflow不支持着色,我在此处使用粗体)
  • real result = Hello
    world

我尝试使用Html.escapeHtml。但是它在API级别16中添加,而我的最低要求是8。

我的问题是如何解决上述问题?

1 个答案:

答案 0 :(得分:2)

您应该使用Spans

Spannables可用于替换TextView文本的部分内容:例如颜色为ForeGroundColorSpan。它甚至可以用于引入与文本内联的图像(文本消息中的表情符号)。

这是一个突出显示<br>部分的硬编码示例。你应该添加正则表达式算法:

<强> MainActivity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = (TextView)findViewById(R.id.helloworld);
        Spannable spannableString = new SpannableString(getString(R.string.hello_world));        
        spannableString.setSpan(new ForegroundColorSpan(Color.RED), 5, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannableString);

    }

<强>的strings.xml

<string name="hello_world">
  <![CDATA[
    Hello <br> World 
  ]]>
</string>

<强> main.xml中

<TextView
    android:id="@+id/helloworld"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

Screenshot highlight <br> tag