繁体   English   中英

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

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

我有一个字符串。

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

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

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

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

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

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

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM