Reputation: 9599
I want to make an application about regex. User input a regex and a test text, and I want to highlight everything in the test text that matches the regex. Now I've made something like this:
// 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>")));
The issue is user may input some string including HTML tags as the test text. For example:
o
Hello<br>world
Hello<br>world
(Since StackOverflow don't support coloring, I use bold here instead)Hello
world
I tried to use Html.escapeHtml
. However it is added in API level 16, while my minimum require is 8.
My question is how to solve the issue above?
Upvotes: 2
Views: 870
Reputation: 18391
You should use Spans:
Spannables can be used to alternate parts of the TextView's text: e.g. color with ForeGroundColorSpan. It can even be used to introduce an image inline with the text (emoticons in a textmessage).
here is a hard coded example highlighting the <br>
part. you should add the regex algorithme:
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" />
Upvotes: 2