代码之家  ›  专栏  ›  技术社区  ›  Siddarth G

如何获取跨越对象中字符的索引?

  •  1
  • Siddarth G  · 技术社区  · 7 年前

    我有这根绳子 String thestring="<p>Abcd® X (CSX) Open Cell</p>" 我用过Html。从中跳过标签打印,如下所示:

    Spanned spst = Html.fromHtml(thestring);
    

    SpannableStringBuilder cs = new SpannableStringBuilder(spst);
            cs.setSpan(new SuperscriptSpan(),thestring.indexOf("®") ,thestring.indexOf("®")+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            cs.setSpan(new RelativeSizeSpan(0.75f), thestring.indexOf("®"),thestring.indexOf("®")+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            content.setText(cs, TextView.BufferType.SPANNABLE);
    

    但这不是上标,对于跨越对象和字符串,索引是不同的,如何获得跨越字符串中的索引?

    1 回复  |  直到 7 年前
        1
  •  2
  •   snachmsm    7 年前

    转换 Spanned String ,这将为您提供“干净”的HTML字符串

    String strippedFromHTMLString = spst.toString();
    

    然后在 setSpan 使用它而不是原始的 thestring

    int indexOfR = strippedFromHTMLString.indexOf("®");
    SpannableStringBuilder cs = new SpannableStringBuilder(spst);
    cs.setSpan(new SuperscriptSpan(),  indexOfR, indexOfR+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    cs.setSpan(new RelativeSizeSpan(0.75f),  indexOfR, indexOfR+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    content.setText(cs, TextView.BufferType.SPANNABLE);