如何在java / android中更改字符串中特定字符的颜色?

时间:2014-08-05 12:03:57

标签: java android

我有一个字符串。

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

如何在String中更改用户在运行时输入的特定字母的颜色。

4 个答案:

答案 0 :(得分:9)

我假设您想要用户选择在字符串中突出显示的特定文本。下面应该可以帮到你。

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

答案 1 :(得分:2)

你可以用简单的方法做到这一点。

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

如果有任何问题,请告诉我。

答案 2 :(得分: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);

试试这个

答案 3 :(得分:0)

您可以通过spanSpan 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