getSpans for Spanned String returns spans out of o

2019-05-07 09:45发布

问题:

I use the following code to sift through a Spanned String saving all bold text as a string in an array:

StyleSpan[] spans = storyText.getSpans(0,
        storyText.length(), StyleSpan.class);
List<String> boldedWords = new ArrayList<String>();
for (StyleSpan span : spans) {
    if (span.getStyle() == Typeface.BOLD) {
        //start
        int s = storyText
                .getSpanStart(span);
        //end
        int e = storyText.getSpanEnd(span);
        boldedWords.add(storyText.subSequence(
                s, e).toString());
    }
}

String[] array = boldedWords
        .toArray(new String[boldedWords.size()]);

However, the Strings I receive back in the array are out of order. For example:

Sentence might be (CAPS represent bold text):

storyText = "This ADJECTIVE NOUN is VERB"

The array I'd get back would be: "Noun, Verb, Adjective" in that order. It should be: "Adjective, Noun, Verb"

Any insight on why this might be happening?

回答1:

Use int nextSpanTransition(int start, int limit, Class kind) to iterate over your spans. This way you get the reading order.