调整使用SpannableString文本对齐文本、SpannableString

2023-09-04 11:40:25 作者:冷雨绝ξǒ..

我已经创建了一个SpannableString,第一个字符,并且比其他的最后2小。它看起来是这样的:

I have created a SpannableString, with the first character, and last 2 smaller than the rest. It looks like this:

sBBBBss

我想对准小字符,以便它们与大文本的顶部对齐,而不是底部(因为它们出现在这里)。

I would like to align the smaller characters so they are aligned with the top of the bigger text, instead of the bottom (as they appear here).

这可能吗?

我想我正在寻找这样的事伪code:

I guess I am looking for something like this pseudo-code:

myAmount.setSpan(新的 RelativeAlignSpan(View.TOP)的,0,1,0);

myAmount.setSpan(new RelativeAlignSpan(View.TOP), 0, 1, 0);

我唯一的其他选择是创建一个新的布局,具有多种TextViews,我填充独立的,不管我取悦对齐。我觉得这是一种混乱的,并且将preFER使用SpannableString方法。

My only other alternative is to create a new layout, with multiple TextViews, that I populate independently, and align however I please. I think this is kind of messy, and would prefer to use the SpannableString approach.

推荐答案

于是,我找到了答案,这个问题是张贴在这里,以帮助未来的家伙。

So I found the answer to this question posting it here to help the next guy.

我创建了一个辅助类包含方法来调整跨度,您可以使用此语法调用它(这是设置的最后2个字符出现就行了更高):

I created a helper class to contain the methods to adjust the Span, you can call it using this syntax (this is setting the last 2 characters to appear higher on the line):

SpannableString contentAmount = new SpannableString(amount);

contentAmount.setSpan(new SuperscriptSpanAdjuster(3.0/5.0), contentAmount.length() - 2, contentAmount.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);

和辅助类是:

/**
 * This is a helper class to help adjust the alignment of a section of text, when using SpannableStrings to set text 
 * formatting dynamically.
 * 
 */
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;

public class SuperscriptSpanAdjuster extends MetricAffectingSpan {
    double ratio = 0.5;

    public SuperscriptSpanAdjuster() {
    }

    public SuperscriptSpanAdjuster(double ratio) {
        this.ratio = ratio;
    }

    @Override
    public void updateDrawState(TextPaint paint) {
        paint.baselineShift += (int) (paint.ascent() * ratio);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        paint.baselineShift += (int) (paint.ascent() * ratio);
    }
}