javaandroidspannablestringspannedspannablestringbuilder

How to get index of a character in spanned object?


i have this string String thestring="<p>Abcd® X (CSX) Open Cell</p>", I have used Html.from to skip the tags from printing like this:

Spanned spst = Html.fromHtml(thestring);

I also want the ® to be superscript, so i have used the following code,

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

But this is not making the ® superscript, the index is different for spanned object and the string, how can i get the index of ® in the spanned string?


Solution

  • convert Spanned to String, this will give you "clean", stripped from HTML string

    String strippedFromHTMLString = spst.toString();
    

    and then in setSpan use it instead of original 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);