Search code examples
androidspannablestring

Android: Change vertical position of superscript when using SuperscriptSpan


In my app, i am trying to use SuperscriptSpanto show a dot. But i want to change the margin of this dot with respect to the top, ideally 0. This is how the result looks like.

I would like the dot to align with the top of the textView, while right now it is somewhere in the middle.

enter image description here

This is my code:

    SpannableStringBuilder cs = new SpannableStringBuilder("MyText.");
    cs.setSpan(new SuperscriptSpan(), 6, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Thanks in advance!


Solution

  • If you want to change the default behavior of SuperscriptSpan, you'll have to create your own custom subclass of it and override both updateDrawState() and updateMeasureState().

    You can look at the source code for SuperscriptSpan to see how they're currently implemented. Something like this will push the dot higher than you see now:

    @Override
    public void updateDrawState(@NonNull TextPaint textPaint) {
        textPaint.baselineShift += (int) ((2 * textPaint.ascent()) / 3);
    }
    
    @Override
    public void updateMeasureState(@NonNull TextPaint textPaint) {
        textPaint.baselineShift += (int) ((2 * textPaint.ascent()) / 3);
    }