【问题标题】:Setting subscript and superscript for specific character in the TextView?为 TextView 中的特定字符设置下标和上标?
【发布时间】:2014-03-22 14:55:00
【问题描述】:

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

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

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

但是结果是这样的:

你可以看到下标后面出现上标。我该如何解决这个问题?我可以用SpannableString解决吗?或者我可以改变下标的位置吗?

【问题讨论】:

  • 我不确定,但您可能可以使用 SubscriptSpan 和 SuperscriptSpan 解决此问题。
    请阅读此post 并尝试。无论如何都会有用的。
  • 通过扩展 ReplacementSpan 创建自己的 Span
  • @pskink 你能解释一下或者告诉我一些链接来帮助我知道怎么做吗?谢谢。

标签: android textview subscript superscript


【解决方案1】:

这个自定义跨度可以帮助您理解基本思想:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多