Android TextView's subscript being clipped off

Most answers suggest to add paddings or to use smaller sub/superscripts. These might be serviceable workarounds, but they don't really solve the problem. Ideally, we want Android to take the sub/superscript into account when calculating line height. I think I found how to do it, and I'm sharing it for people googling this issue.

    SpannableStringBuilder sb = new SpannableStringBuilder("X2");
    sb.setSpan(new SuperscriptSpan(), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(sb, BufferType.SPANNABLE);

The trick is in BufferType.SPANNABLE. Apparently it makes TextView pay more attention to the markup and calculate line heights properly.


This solution worked for me.

Superscripted text is usually made smaller when the browser renders it, that doesn't seem to happen here so you can replicate that (and solve this problem) by doing this:

someTextView.setText(Html.fromHtml("Some text<sup><small>1</small></sup>"));

For subscript a slight variation to the above suggestion is needed, two small tags:

    textView.setText(Html.fromHtml(
        "HCO<sub><small><small>3</small></small></sub>));