getSpans for Spanned String returns spans out of order?

送分小仙女□ 提交于 2019-12-07 10:03:01

问题


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.



来源:https://stackoverflow.com/questions/25097733/getspans-for-spanned-string-returns-spans-out-of-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!