0

I need your help to make a color function. I'd like to create something like this

I've an edittext and I want to put in color part of string , but with a special input example :

if the user type : ^1Hi ^2Stack^3Over^4Flow !
"Hi" = red color , "Stack" = green color , "Over" = blue color and "Flow" = orange color.

how to do this?

Mike Mertsock
  • 11,825
  • 7
  • 42
  • 75
Clyx
  • 11
  • 6
  • you need to parse such text and replace it with html tags http://stackoverflow.com/questions/2730706/highlighting-text-color-using-html-fromhtml-in-android – Selvin Aug 27 '13 at 13:18
  • i've already looked on this post , but i dont know how to know if the symbol "^" has been typed , thanks – Clyx Aug 27 '13 at 13:30

4 Answers4

2

enter image description hereYou could Use Spannable string to achieve this:

SpannableStringBuilder builder = new SpannableStringBuilder();

String red = "RedText";
SpannableString str1= new SpannableString(red);
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
builder.append(str1);

String white = "WhiteText";
SpannableString str2= new SpannableString(white);
str2.setSpan(new ForegroundColorSpan(Color.WHITE), 0, white.length(), 0);
builder.append(str2);

String blue = "BlueText";
SpannableString str3 = new SpannableString(blue);
str3.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blue.length(), 0);
builder.append(str3);

mTextView.setText(builder, BufferType.SPANNABLE);
Gaurav Arora
  • 1,805
  • 13
  • 13
1

You can try following:

String styledText = "This is <font color='red'>Hi</font>"+" "+"<font color='green'>Stack</font>"+" "+"<font color='blue'>Over</font>"+" "+"<font color='orange'>Flow</font>";

textview.setText(Html.fromHtml(styledText));
Ritesh Gune
  • 16,629
  • 6
  • 44
  • 72
0

You have to use StringTokenizer class with delimiter "^" and then have to get first char from each word. This number can be an index in your color array for example List

EDIT: Create stringTokenizer like this

StringTokenizer sT = new StringTokenizer(yourString, "^");

while(sT.hasMoreTokens()) {
String myColorString = sT.nextToken();
int color = myColorString.charAt(0);
String text = myColorString.substring(1, myColorString.length-1);
}

then you can get color by color variable and color your String text :).

When you will have number more than 2 chars you can use regular expression, but problem will appear when you want to have number on start of your String which you want to color :);

I think it will be better to make something like this 1;myString^2;myString2^3;myString3

and the you can use string tokenizer for each number;myString too.

Mathew1990
  • 327
  • 2
  • 17
-2

write a function that receive the whole String and cut it in the seperate words (seperate by blanks) and give every word a color by a counter++.