Get Spannable String from EditText

Rahul Chauhan picture Rahul Chauhan · Oct 5, 2013 · Viewed 10.7k times · Source

I have set a SpannableString to an EditText, now I want to get this text from the EditText and get its markup information. I tried like this:

SpannableStringBuilder spanStr = (SpannableStringBuilder) et.getText();
int boldIndex = spanStr.getSpanStart(new StyleSpan(Typeface.BOLD));
int italicIndex = spanStr.getSpanStart(new StyleSpan(Typeface.ITALIC));

But it gives index -1 for both bold and italic, although it is showing text with italic and bold.

Please help.

Answer

KMDev picture KMDev · Oct 5, 2013

From the code you've posted, you're passing new spans to spanStr and asking it to find them. You'll need to have a reference to the instances of those spans that are actually applied. If that's not feasible or you don't want to track spans directly, you can simply call getSpans to get all the spans applied. You can then filter that array for what you want.

If you don't care about the spans in particular, you can also just call Html.toHtml(spanStr) to get an HTML tagged version.

edit: to add code example

This will grab all applied StyleSpans which is what you want.

    /* From the Android docs on StyleSpan: "Describes a style in a span. 
     * Note that styles are cumulative -- both bold and italic are set in 
     * separate spans, or if the base is bold and a span calls for italic, 
     * you get bold italic. You can't turn off a style from the base style."*/
StyleSpan[] mSpans = et.getText().getSpans(0, et.length(), StyleSpan.class);

Here's a link to the StyleSpan docs.

To pick out the spans you want if you have various spans mixed in to a collection/array, you can use instanceof to figure out what type of spans you've got. This snippet will check if a particular span mSpan is an instance of StyleSpan and then print its start/end indices and flags. The flags are constants that describe how the span ends behave such as: Do they include and apply styling to the text at the start/end indices or only to text input at an index inside the start/end range).

 if (mSpan instanceof StyleSpan) { 
        int start = et.getSpanStart(mSpan);
        int end = et.getSpanEnd(mSpan);
        int flag = et.getSpanFlags(mSpan);
        Log.i("SpannableString Spans", "Found StyleSpan at:\n" +
                "Start: " + start + 
                 "\n End: " + end + 
                 "\n Flag(s): " + flag);
 }