如何在 TextView 中创建垂直对齐的上标和下标 [英] How to create vertically aligned superscript and subscript in TextView

查看:31
本文介绍了如何在 TextView 中创建垂直对齐的上标和下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下图示例中:

如何使上标和下标数字对齐以生成如下所示的通用科学记数法

How can I make both the superscript and subscript numbers to be aligned to produce a common scientific notation like below

TextView 中?如果有使用 SpannableReplacementSpan 的方法,我希望看到一个工作示例.谢谢.

in TextView? If there is a way using Spannable or ReplacementSpan I would like to see a working example. Thank you.

推荐答案

您可能想尝试这样的事情.

You might want to try something like this.

它基本上是一个 ReplacementSpan,它将应用它的文本分成两部分,然后在画布上绘制它们.尺寸因子和 y 平移是经过精心挑选的.我希望它是有用的(或者至少你或其他人可以在它的基础上发展).

It's basicall a ReplacementSpan that takes the text it's applied on, separates it into two parts, and draws them on the canvas. The size factor and y translation are somewhat hand-picked. I hope it's useful (or at least that you or someone else can build on it).

public class SuperSubSpan extends ReplacementSpan
{
    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm)
    {
        text = text.subSequence(start, end);
        String[] parts = text.toString().split(",");

        Paint p = getSuperSubPaint(paint);
        return (int) Math.max(p.measureText(parts[0]), p.measureText(parts[1]));
    }

    private static TextPaint getSuperSubPaint(Paint src)
    {
        TextPaint paint = new TextPaint(src);
        paint.setTextSize(src.getTextSize() / 2.5f);
        return paint;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint)
    {
        text = text.subSequence(start, end);
        String[] parts = text.toString().split(",");

        Paint p = getSuperSubPaint(paint);

        float width1 = p.measureText(parts[0]);
        float width2 = p.measureText(parts[1]);
        float maxWidth = Math.max(width1, width2);

        canvas.drawText(parts[0], x + (maxWidth - width1), y - (bottom - top) / 3f, p);
        canvas.drawText(parts[1], x + (maxWidth - width2), y + (bottom - top) / 10f, p);
    }
}

然后将其用作:

Spannable str = new SpannableString("9,4Be -> 2000,127Jo");
str.setSpan(new SuperSubSpan(), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new SuperSubSpan(), 9, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mTextView.setText(str);

产生以下结果:

更好的解决方案是为这些字符串使用特殊格式(例如 "{9,4}Be -> {2000,127}Jo")并使用正则表达式处理字符串并添加相应的SuperSubSpans,这样您就不需要手动添加了.但实际的 Span 部分或多或少是相同的.

A slightly better solution would be to have a special format for these strings (e.g. "{9,4}Be -> {2000,127}Jo") and have a regular expression process the string and add the corresponding SuperSubSpans, just so that you don't need to this manually. But the actual Span part would be more or less the same.

这篇关于如何在 TextView 中创建垂直对齐的上标和下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆