在TextView中为特定字符设置下标和上标?

时间:2014-02-21 07:59:14

标签: android textview subscript superscript

有没有办法在TextView中为特定字符设置下标和上标?我想显示一个如下所示的文本:

enter image description here

所以,我尝试了这段代码:

TextView tv1 = ... ;
String latex = "\u222E";
tv1.setText(Html.fromHtml(latex + "<sup>200</sup><sub>2</sub> f(x)dx"));

但结果如下:

enter image description here

你可以看到上标出现在下标之后。我怎么能解决这个问题?我可以用SpannableString解决吗?或者我可以改变下标的位置吗?

1 个答案:

答案 0 :(得分:2)

此自定义范围可以帮助您了解基本理念:

class SupSubSpan extends ReplacementSpan {
    private String sup;
    private String sub;

    public SupSubSpan(String sup, String sub) {
        this.sup = sup;
        this.sub = sub;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
        return (int) Math.max(paint.measureText(sup), paint.measureText(sub));
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        canvas.drawText(sup, x, y + paint.ascent() / 2, paint);
        canvas.drawText(sub, x, y - paint.ascent() / 2, paint);
    }
}