3

I have a String.

String text= //Some String That I know
String textToBeColored = //Some Letter User enters at run time

How can I change the color of a specific letter that user enters at run time in my String.

Krupa Patel
  • 3,309
  • 3
  • 23
  • 28
BST Kaal
  • 2,993
  • 6
  • 34
  • 52

4 Answers4

12

I assume that you want something like particular text that user selects to be highlighted in the string. Below should help you do it.

String text = "abcada";
String textToBeColored = "a";

String htmlText = text.replace(textToBeColored,"<font color='#c5c5c5'>"+textToBeColored +"</font>");
// Only letter a would be displayed in a different color.
txtView.setText(Html.fromHtml(htmlText);
nandur
  • 134
  • 10
ngrashia
  • 9,869
  • 5
  • 43
  • 58
2

You can do this with simple way.

SpannableStringBuilder builder = new SpannableStringBuilder();

String red = "user's word is red";
SpannableString redSpannable= new SpannableString(red);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
builder.append(redSpannable);

mTextView.setText(builder, BufferType.SPANNABLE);

Let me know if any problem.

OmerFaruk
  • 292
  • 2
  • 13
0
TextView TV = (TextView)findViewById(R.id.textView1); 
    Spannable WordtoSpan = new SpannableString("I this is just a test case");        
    WordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 4, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    TV.setText(WordtoSpan);

try this

DKV
  • 1,767
  • 3
  • 28
  • 49
0

You can do this by setSpan on SpannableStringBuilder(Text)

final SpannableStringBuilder sb = new SpannableStringBuilder("text");
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(234, 123, 121));  


sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 
//0 is starting index
//4 is ending index

You can use sb as string 
GOLDEE
  • 2,318
  • 3
  • 25
  • 49