Adjusting text alignment using SpannableString

前端 未结 1 1583
终归单人心
终归单人心 2021-02-04 07:22

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

sBBBBss

I would

1条回答
  •  遥遥无期
    2021-02-04 08:23

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

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

    and the helper class is:

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

    0 讨论(0)
提交回复
热议问题