我需要获取AttributedString上应用属性的索引。

因此,假设您有一个带有已应用属性的AttributedString,在我的情况下为下标/上标。

 AttributedString as1 = new AttributedString("1234567890");
 as1.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 5, 7);


我已经设法通过获得第一个字符,其中子/上标开始

        int startIdx = as1.getIterator().getRunLimit(TextAttribute.SUPERSCRIPT);


最后,我需要派生所应用属性的endIdx,但是我找不到解决此问题的方法。
方法文档说,即使在相关的Java文档中,也总是返回第一个字符索引。没有办法获取应用属性的endindex吗?

最佳答案

我认为,已经找到解决该问题的非常难看的方法。
对于那些感兴趣的人:

   AttributedString as1 = new AttributedString("0123456789");
   as1.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 6, 9);

   AttributedCharacterIterator it = string.getIterator();

   int startIdx = -1, endIdx = -1;

   while(it.current() != AttributedCharacterIterator.DONE) {
        boolean attributeExists = (Integer) it.getAttribute(TextAttribute.SUPERSCRIPT) != null ? true : false;
        if (attributeExists && startIdx == -1)
            startIdx = it.getIndex();

        if (attributeExists && startIdx != -1)
            endIdx = it.getIndex();

        it.next();
    }


我认为此解决方案仅适用于AttributedStrings上的单个应用属性。就我而言,这已经足够了。
我不会接受我的回答,因为我会对更优雅的方式感兴趣。

08-05 03:38