0

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());
SilenT612
  • 43
  • 1
  • 7
  • 1
    You can use spannable string. Check with below answer. http://stackoverflow.com/questions/3282940/set-color-of-textview-span-in-android – prabhat Jan 13 '14 at 17:16

1 Answers1

0

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

Community
  • 1
  • 1
nKn
  • 13,691
  • 9
  • 45
  • 62
  • But can I put the string event.getSender() and event.getMessage() in it ? I mean can they get colored as well ? – SilenT612 Jan 13 '14 at 17:16
  • Yes, of course, but in that case you'll probably want to use `SpannableStringBuilder` instead of `Html` because the first one gives you the possibility of coloring just a part of the string defined by char indexes. I recommend having a look at the link I provided, that does exactly what you want. – nKn Jan 13 '14 at 17:27
  • I frist tried this one http://stackoverflow.com/a/4897386/3191131 but the app crashes ... So I guess i'll try the first code on your link and I'll see what it gives. – SilenT612 Jan 13 '14 at 17:52
  • The app still crashes with SpannableStringBuilder any solutions ? – SilenT612 Jan 13 '14 at 18:47
  • Update your post with the crash you're getting. – nKn Jan 13 '14 at 18:48
  • I can't find the crash report, I'm new to Eclipse. I was debugging with my phone. – SilenT612 Jan 13 '14 at 23:12
  • If you're using Eclipse, open the LogCat window, there should appear the error. Go to Window -> Show view -> LogCat (if it doesn't appear, click on Other and type LogCat). – nKn Jan 13 '14 at 23:18