Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am developing an application in which there will be a search screen where user can search for specific keywords and that keyword should be highlighted. I have found Html.fromHtml method.

But I will like to know whether its the proper way of doing it or not.

Please let me know your views on this.

share|improve this question
check out for an working example. javatechig.com/2013/04/07/how-to-display-html-in-android-view – Nilanchala Apr 7 at 20:29

4 Answers

up vote 62 down vote accepted

Or far simpler than dealing with Spannables manually, since you didn't say that you want the background highlighted, just the text:

String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);
share|improve this answer
It's worth noting, that Html.fromHtml is slower than SpannableString, because it involves parsing. But for a short text it doesn't matter – Michał K Dec 8 '12 at 19:01
There appears to be another solution at link. See the answer by Legend. – Kenneth Evans Jan 15 at 22:25

This can be achieved using a Spannable String. You will need to import the following

import android.text.SpannableString; 
import android.text.style.BackgroundColorSpan; 
import android.text.style.StyleSpan;

And then you can change the background of the text using something like the following:

TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Add all your funky text in here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);

Where this will highlight the charecters at pos 1 - 4 with a red color. Hope this helps!

share|improve this answer
Thanks a lot for replying. – sunil May 31 '10 at 14:11

Alternative solution: Using a WebView instead. Html is easy to work with.

WebView webview = new WebView(this);

String summary = "<html><body>Sorry, <span style=\"background: red;\">Madonna</span> gave no results</body></html>";

webview.loadData(summary, "text/html", "utf-8");
share|improve this answer
Thanks a lot for replying and letting me know the use of Webview and HTML. – sunil May 31 '10 at 14:27

Using color value from xml resource:

int сolor = getResources().getColor(R.color.label_color);
String сolorString = String.format("%X", labelColor).substring(2); // !!strip alpha value!!

Html.fromHtml(String.format("<font color=\"#%s\">text</font>", сolorString), TextView.BufferType.SPANNABLE); 
share|improve this answer
nicely done. useful to be able to use colors from your apps resources. – domji84 May 7 at 11:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.