BST Kaal
BST Kaal

Reputation: 3033

How to change the color of a specific character in a string in java / android?

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.

Upvotes: 3

Views: 11844

Answers (4)

ngrashia
ngrashia

Reputation: 9884

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);

Upvotes: 12

GOLDEE
GOLDEE

Reputation: 2318

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 

Upvotes: 0

DKV
DKV

Reputation: 1767

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

Upvotes: 0

OmerFaruk
OmerFaruk

Reputation: 292

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.

Upvotes: 2

Related Questions