Android TextView's subscript being clipped off

Tawani picture Tawani · Nov 16, 2009 · Viewed 8.6k times · Source

The Android TextView clips off my text subscripts (see image below) even when I use android:layout_height="wrap_content" for the TextView. Is there a fix/work-around for this?

alt text

P/S: Superscripts work fine

Note: padding doesn't work.

  • I tried even adding a padding of 50dip but it did not help.
  • I can use an absolute height such as 50dip but that messes everything up when I need text to wrap around.

Sample Code:

mtTextView.setText(Html.fromHtml("HC0<sub>3</sub>"));

Answer

Nick Frolov picture Nick Frolov · Aug 21, 2015

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.