androidandroid-layouttextviewspannablestringandroid-textattributes

How do I change color of a certain part of my textview?


I am using 2 parts in a textview, 1st part is date another is name and email. They are both referenced in the same textview. I would like to change the color of the date to give it a different visual it from name and email. is it possible to do this without actually adding a whole new textview for name and email? Here's my code so far:

String nameandemail;
holder.mytext.setText(String.valueOf(dateFormat.format(new Date(msg.getDate())) + " " + nameandemail + ": "));

How do I make it such that I can set the color of date with holder.mytext.setTextColor(Color.white) and for the nameandemail string something like green?

Thanks!


Solution

  • you could define a String in your strings.xml file

     <string name="test2">&lt;font color=\'#FFFFFF\'>%1$s&lt;/font>  -- &lt;font color=\'#00FF00\'>%2$s&lt;/font></string>
    

    and then programmatically

    TextView tv = (TextView) findViewById(R.id.test);
     tv.setText(Html.fromHtml(getString(R.string.test2, String.valueOf(dateFormat.format(new Date(msg.getDate())), nameandemail)));