Reputation: 34507
Hello I am working on demo application where I need to set the yellow background color of selected text in a string.
For ex :
String str = "Na Adam ne ne yere Hawa: Na Adam xwoo xbabarima";
I want to set the white background color of all words except Adam
. I need to set the background color of Adam
word to yellow.
Thanks in advance.
Upvotes: 3
Views: 1906
Reputation: 458
This formatting would be suitable for JLabel:
JLabel label = new JLabel("<html>Na <font bgcolor='yellow'>Adam</font> ne ne yere Hawa: Na <font bgcolor='yellow'>Adam</font> xwoo xbabarima</html>");
Upvotes: 0
Reputation: 11899
Use the following code:
String str = "Na Adam ne ne yere Hawa: Na Adam xwoo xbabarima";
String stringToColor = "Adam";
int ofe = str.indexOf(stringToColor,0);
Spannable WordtoSpan = new SpannableString(str);
for(int ofs=0;ofs<str.length() && ofe!=-1;ofs=ofe+1)
{
ofe = str.indexOf(stringToColor,ofs);
if(ofe == -1)
break;
else
{
WordtoSpan.setSpan(new BackgroundColorSpan(Color.YELLOW), ofe, ofe+stringToColor.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
}
}
Output:
Upvotes: 3
Reputation: 4792
You can use some html:
String adam = "<font color=#FFFF00>Adam</font>";
String str = "Na Adam ne ne yere Hawa: Na Adam xwoo xbabarima";
String newString = str.replaceAll("Adam", adam);
t.setText(Html.fromHtml(newString));
Upvotes: 2
Reputation: 2840
you can format the text as HTML such as:
String htmlText = "<font color=#000000>Na </font> <font color=#00FF00>Adam </font> <font color=#000000>ne ne yere Hawa: Na </font> <font color=#00FF00>Adam </font> <font color=#000000>xwoo xbabarima</font>"
tView.setText(Html.fromHtml(htmlText))
In order to make it more dynamic you can add some regular expression functionality for identifying ur keywords which should be of a different color and create the HTML text
Upvotes: 0
Reputation: 11030
Look at this question here on setting the color of a TextView.
You can use
textView1.setTextColor(getResources().getColor(R.color.mycolor))
or
textview1.setBackgroundColor(Color.parseColor("#ffffff"));
or
textview1.setBackgroundColor(Color.RED);
or
textView1.setBackgroundColor(R.color.black);
Upvotes: 0
Reputation: 2642
You should look into the JEditorPane class, it allows you to do things like these easily:
JEditorPane editorPane = new JEditorPane("text/html","<font color=\"red\">this will be red</font><font color=\"blue\">, and this will be blue</font>");
Upvotes: 0