如何在java/android中更改字符串中特定字符的颜色?
我有一根绳子如何在java/android中更改字符串中特定字符的颜色?,java,android,Java,Android,我有一根绳子 String text= //Some String That I know String textToBeColored = //Some Letter User enters at run time 如何更改用户在运行时在字符串中输入的特定字母的颜色 我假设您希望在字符串中突出显示用户选择的特定文本之类的内容。下面应该可以帮助你做到这一点 String text = "abcada"; String textToBeColored = "a"; String htmlTex
String text= //Some String That I know
String textToBeColored = //Some Letter User enters at run time
如何更改用户在运行时在字符串中输入的特定字母的颜色 我假设您希望在字符串中突出显示用户选择的特定文本之类的内容。下面应该可以帮助你做到这一点
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);
String text=“abcada”;
字符串textToBeColored=“a”;
字符串htmlText=text.replace(textToBeColored,“+textToBeColored+”);
//只有字母a将以不同的颜色显示。
setText(Html.fromHtml(htmlText);
您可以用简单的方法来实现这一点
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);
如果有任何问题,请告诉我
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);
尝试此操作您可以通过在SpannableStringBuilder(文本)上设置span来完成此操作
到目前为止有什么尝试吗?我已经搜索了,发现了一些有用的东西,
txt.setText(Html.fromHtml(“您的内容”)
您也在哪里输出字符串?但问题是,我必须知道需要着色的字母。字符串在UI中如何显示?它给出了一个异常:java.lang.IndexOutOfBoundsException:setSpan(0…9)结束于长度1之外
第4行,红色。length()应更改为红色。length()-1,因为数组的索引以0开头
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