简体   繁体   中英

Get TextView.append to set color on Android

I am developping a little chat application on Android and I want to make the usernames colored whenever they send message so basicly I have a TextView which displays messages

outputView.append("\n"+event.getSender()+": "+event.getMessage());

For now I have that, the problem is that I have a single TextView which display the username and the messages all at one. How can I give a color to the username which is event.getSender()

Thank you !

EDIT : As NKN told me to do I changed it to this. Yet, I still can't get it to work, it simply crashes ... Have I written anything wrong ?

final SpannableStringBuilder sb = new SpannableStringBuilder(event.getSender());
   final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158)); 

   // Span to set text color to some RGB value
   final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); 

   // Span to make text bold
   sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

   // Set the text color for first 4 characters
   sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

   // make them also bold
   outputView.setText("\n"+sb+": "+event.getMessage());

You may use Html class, for example:

tv.setText(Html.fromHtml("<font color="#FF0000">This is a red text</font> and this one is <b>bold</b>");

Further, you may also use SpannableStringBuilder , I recommend reading this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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