Search code examples
androidstringcolorscoding-styletextview

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


Solution

  • 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