Chris Umbel

Rich-Style Formatting of an Android TextView

Even a developer-friendly mobile platform like Android can have a developer feeling a little lost when trying to perform simple tasks when you're unfamiliar with the platform.

One of these simple, however poorly documented, tasks is rich-style text formatting within a TextView.

SpannableString

While it's possible to set a TextView's text property to a simple String and configure the TextView to have the formatting you desire you're then limited in how granular you can control the formatting within the TextView itself. The SpannableString class allows you to easily format certain pieces (spans) of a string one way and other pieces another by applying extensions of CharacterStyle (i.e. ForegroundColorSpan) via the setSpan method.

In the end this isn't limited to formatting. It also allows the developer to add behaviors to spans such as reacting to click events.

Example

Here's an example onCreate method of an Activity. This assumes there's a main.xml layout with a TextView identified by "rich_text".

Essentially this code will set a TextView's text to the familiar, "Lorem ipsum dolor sit amet" and perform the following formatting:

  • Make "Lorem" red
  • Make "ipsum" a 1.5 times bigger than what the TextView's setting
  • Make "dolor" display a toast message when touched
  • Strike through "sit"
  • Make "amet" twice as big as the TextView's setting, green and a link to this site

 
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    richTextView = (TextView)findViewById(R.id.rich_text);

    // this is the text we'll be operating on
    SpannableString text = new SpannableString("Lorem ipsum dolor sit amet");

    // make "Lorem" (characters 0 to 5) red
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);

    // make "ipsum" (characters 6 to 11) one and a half time bigger than the textbox
    text.setSpan(new RelativeSizeSpan(1.5f), 6, 11, 0);

    // make "dolor" (characters 12 to 17) display a toast message when touched
    final Context context = this;
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Toast.makeText(context, "dolor", Toast.LENGTH_LONG).show();
        }
    };
    text.setSpan(clickableSpan, 12, 17, 0);

    // make "sit" (characters 18 to 21) struck through
    text.setSpan(new StrikethroughSpan(), 18, 21, 0);

    // make "amet" (characters 22 to 26) twice as big, green and a link to this site.
    // it's important to set the color after the URLSpan or the standard
    // link color will override it.
    text.setSpan(new RelativeSizeSpan(2f), 22, 26, 0);
    text.setSpan(new URLSpan("http://www.chrisumbel.com"), 22, 26, 0);
    text.setSpan(new ForegroundColorSpan(Color.GREEN), 22, 26, 0);

    // make our ClickableSpans and URLSpans work
    richTextView.setMovementMethod(LinkMovementMethod.getInstance());

    // shove our styled text into the TextView        
    richTextView.setText(text, BufferType.SPANNABLE);
}

The results of which will look something like:

Note that we set the TextView's movement method to a LinkMovementMethod instance. Without that the ClickableSpan and URLSpans won't perform their intended actions.

Next Steps

This covers the fundamental concepts, but there are many extensions of CharacterStyle I haven't covered here. Check out the CharacterStyle documentation for more details.

Also note that a SpannableStringBuilder is provided for building large spannables from smaller pieces.

Sat Aug 28 2010 18:25:02 GMT+0000 (UTC)

33 Comments Comment Feed - Permalink
Thanks a lot for this article , need this for my project 

And for concatenation we can use TextUtils.concat() which keep the spans
by Arialia on Fri Apr 15 2011 08:39:12 GMT+0000 (UTC)
Very interesting article.
I thank you so much to have proposed this pratical example that enables to understand this notion which is not well developped in the Android's documentation.
Hope you're keep on doing such good stuff ! ;o)
by Android's beginner on Wed Nov 09 2011 20:35:13 GMT+0000 (UTC)
Thanks a lot for this article , need this for my project 

And for concatenation we can use TextUtils
by chloe bags on Sat Nov 26 2011 07:15:42 GMT+0000 (UTC)
Thanks a lot. 
Very nice example
by Gaurang Patel on Tue Feb 07 2012 09:36:53 GMT+0000 (UTC)
Thanks a bunch, great example and exactly what I was after.
by Jason on Thu Feb 16 2012 10:54:45 GMT+0000 (UTC)
Thanks a lot!
Finally a clear answer and how to!!
by Noel on Mon Mar 26 2012 21:10:43 GMT+0000 (UTC)
great...
by anon on Thu May 03 2012 07:45:56 GMT+0000 (UTC)
Gr8 Article
by Sumit K on Tue Jun 26 2012 08:59:34 GMT+0000 (UTC)
Thanks!
by anon on Tue Jul 17 2012 09:47:15 GMT+0000 (UTC)
Great post Chris! Keep it up!!!
by Greg on Thu Aug 23 2012 10:21:04 GMT+0000 (UTC)
The font family you use on your website is not pleasing to the eye.
by Ben on Tue Sep 11 2012 11:34:55 GMT+0000 (UTC)
I'm sorry you don't like it, Ben.
by Chris Umbel on Sat Nov 17 2012 21:41:26 GMT+0000 (UTC)
Nice Article Chris. Keep doing it , it cleary explains about Spannable string and spans.
by Raj on Thu Jun 27 2013 18:16:47 GMT+0000 (UTC)
Thanks - really helpful.
by Uwais on Tue Dec 17 2013 11:51:23 GMT+0000 (UTC)
Thanks , it's really helpful.
by Brijesh Patel on Thu Feb 06 2014 07:06:38 GMT+0000 (UTC)
Thanks a lot, it really helpful.
by xzoomeye on Sat Feb 15 2014 03:16:14 GMT+0000 (UTC)
Thanks, simple and clean explanation
by Diego Gonzalez on Fri Mar 14 2014 16:26:18 GMT+0000 (UTC)
Thank you, sir! Very helpful article.
by Ondra on Tue Jul 29 2014 11:04:17 GMT+0000 (UTC)
nice
by tanveer.anjum@yahoo.com on Sat Nov 22 2014 09:20:28 GMT+0000 (UTC)
thanks, now I understand :)
by Bruce Wayne on Mon Jan 19 2015 09:04:19 GMT+0000 (UTC)
Nice . Thanks
by Dharmik on Sat Jan 31 2015 11:11:09 GMT+0000 (UTC)
Hi! Do you use Twitter? I'd like to follow you if that would be 
ok. I'm absolutely enjoying your blog and look forward to new posts.
by taking online surveys on Mon May 25 2015 16:04:05 GMT+0000 (UTC)
Asking questions are genuinely good thing if you are not 
understanding anything fully, but this paragraph provides nice understanding 
even.
by Download Nitro Nation Online Hack Tool v1.2.9 No Survey on Wed May 27 2015 04:12:27 GMT+0000 (UTC)
I am truly happy to read this weblog posts which 
contains tons of useful facts, thanks for providing these 
information.
by www.otturazione.com on Wed May 27 2015 07:49:05 GMT+0000 (UTC)
For most up-to-date news you have to visit internet and on the web I found this web page as a best web site for newest updates.
by Www.noleggioautolecce.Com on Wed May 27 2015 14:18:29 GMT+0000 (UTC)
Hello! I know this is kinda off topic however I'd figured I'd ask.
Would you bbe interested inn exchanging links or 
maybe guest authoring a blog article or vice-versa? My site goes over a lot of 
tthe samke subjects as yours andd I believe we could greatly benefit froom each 
other. If you are interestted feel free to send 
me an email. I look forward to hearing from you!

Excellent blog byy the way!
by m88 on Wed May 27 2015 15:39:27 GMT+0000 (UTC)
is this possible in ontouch event ?
because i tried its selected all the string instead of selected word from textview

do you have any idea about what it is ?

thanks in advance
by Rahul on Thu May 28 2015 13:09:07 GMT+0000 (UTC)
La+compa%F1%EDa+es+entre+las+punteras+en+la%A0venta+de+botas+de+f%FAtbol%2C+de+ah%ED+que+se+comprometen+a+hacerte+llegar+tu+%0D%0Apedido+en+menos+de+cuarenta+y+ocho+horas.
by www.blogigo.com on Fri Jun 05 2015 11:50:47 GMT+0000 (UTC)
If you are going for finest contents like I do, only visit this website every day since it provides quality contents, thanks
by london merton escorts on Wed Jul 01 2015 01:31:45 GMT+0000 (UTC)
I am really impressed with your writing skills and also with the layout on your weblog.

Is this a paid theme or did you customize it yourself?
Anyway keep up the nice quality writing, it is rare to 
see a nice blog like this one these days.
by www.uilfplnovara.it on Sat Jul 25 2015 09:52:24 GMT+0000 (UTC)
I enjoy what you guys are up too. This sort of clever work and reporting!
Keep up the terrific works guys I've incorporated you guys to our blogroll.
by IRS Back Tax Help on Sat Aug 08 2015 23:22:16 GMT+0000 (UTC)
The company is staffed with accredited tax obligation professionals to help customers 
with their tax obligation relief.
by atx tax software help on Sun Aug 09 2015 13:00:41 GMT+0000 (UTC)
Amazing job man!
by ash on Sun Aug 16 2015 03:26:16 GMT+0000 (UTC)
Add a comment
Name
E mail (Private)
URL
Follow Chris
RSS Feed
Twitter
Facebook
CodePlex
github
LinkedIn
Google