Lukap
Lukap

Reputation: 31963

Color and style manipulation on textview

ok imagine that we have text like this

String s="123 45678 91011122314 1516";

now my problem is that I want so say

textview.setText(stylemystring(s));

and I want '123' to be bold and red, 45678 to be italic and blue, and so so

I find it quite problematic when styling these thing , there are solutions with htmlformat but the thing is that the size of the text that should be red or blue is dynamic so I need something more flexible.

thanks

Upvotes: 2

Views: 3910

Answers (2)

Gregory
Gregory

Reputation: 4424

Something like this should work :

    SpannableStringBuilder text = new SpannableStringBuilder("123 45678 91011122314 1516");
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    text.setSpan(new ForegroundColorSpan(Color.BLUE), 4, 9, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    text.setSpan(new StyleSpan(Typeface.BOLD), 4, 9, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(text, TextView.BufferType.SPANNABLE);

You can add different styles to different parts of the String. Based on http://developer.android.com/resources/faq/commontasks.html#selectingtext

Upvotes: 12

Ophidian
Ophidian

Reputation: 584

I think you'll have to split it up in different strings to achieve that though.

Take a look at this link

I think it has what you're looking for.

Upvotes: 2

Related Questions