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

How to get index of a character in spanned object?

我有这个字符串 String thestring="<p>Abcd® X (CSX) Open Cell</p>", 我已经使用 Html.from 像这样跳过打印标签:

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);

但是这不是制作 ® 上标,跨对象和字符串的索引不同,如何获取 ® 在跨字符串中的索引?

Spanned 转换为 String,这将为您提供 "clean",从 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);