Is there any example about Spanned and Spannable text

I'm struggling with using EditText and Spannable text object, These days, I've read API documents around ten times, even I'm not certain that I understand correctly. So I'm looking for a kind of example which show me how to utilize EditText and Spannable.


Solution 1:

Since you don't specify what you can't grasp from the API it's hard to answer your questions (short answer: rewrite your question to a specific questions rather than a general one).

A typical Spannable-example is something like this to turn selected text in an EditText into Italic:

Spannable str = mBodyText.getText(); 
if(mBodyText.getSelectionEnd() > mBodyText.getSelectionStart()) 
  str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),  
                      mBodyText.getSelectionStart(), mBodyText.getSelectionEnd(),  
                      Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
else
  str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC),
              mBodyText.getSelectionEnd(),
              mBodyText.getSelectionStart(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

This is cut and pasted from something else, so your direct-pastability might have suffered, but it at least shows a working example of a Spannable (in this case a StyleSpan). In the API you can find the other types of Spans (notably ImageSpan, which is a common questions among newly converted droiders).

Solution 2:

I'm just starting to try to figure it out too, and it seems unnecessarily tricky.

Here's a working method to add NEW spannable text to an existing view. I wanted to add colored text to a view, and this seemed like the only way to do it.

Though it feels like an ugly hack, you can create a dummy TextView (not shown anywhere) and style the text there, then append that styled text to wherever you want. Credit for it goes to iifuzz at anddev.org. My code looks like so:

    spanbuffer = new TextView(context);
    spanbuffer.setText(newText, TextView.BufferType.SPANNABLE);
    Spannable s = (Spannable) spanbuffer.getText();
    s.setSpan(new ForegroundColorSpan(Color.RED), 0, newText.length() - 1, 0);
    this.append(s);

I think you're supposed to be able to create new spannable text using the SpannableFactory, like so:

    Spannable s = Spannable.Factory.getInstance().newSpannable(newText);

but I couldn't get this text to actually show new span effects, so I gave up.