pengwang
pengwang

Reputation: 19946

string format and line break

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

Answers (2)

Jayp
Jayp

Reputation: 822

String s="19831014\n"+"linknum"+i+"cool";

"\n" is a line break.

Upvotes: 6

Kartik Domadiya
Kartik Domadiya

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

Related Questions