Reputation: 19946
I want to code finish string format, I have a
String s="19831014"+"linknum"+i+"cool";
I want to this s have a format link this:
s=<red>19831014</red>+"//n" //line break
+<green>"linknum"</green> +i+"cool"
Can you help?
Upvotes: 0
Views: 7513
Reputation: 29968
String
doesnot have Color but the thing that displays a String
has.
But you can convert your String
object to SpannableString
which allows user to add effects like Bold, italics, Underline, Colored Text Portions etc.
if you want to display String with different colors you have to use ForegroundColorSpan
For example :
SpannableString colouredString =new SpannableString("Red, Green, Blue.");
colouredString.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
colouredString.setSpan(new ForegroundColorSpan(0xFF00FF00), 5, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
colouredString.setSpan(new ForegroundColorSpan(0xFF0000FF), 12, colouredString.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
For changing the Background Color you have to use BackgroundColorSpan
:
For Example :
coloredString.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
now you can use this colouredString
for showing it in EditText
and TextView
For giving different styles you can use StyleSpan
Reference Example: http://developer.android.com/resources/faq/commontasks.html#selectingtext
Upvotes: 3