Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting text alignment using SpannableString

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

Is this possible?

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

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

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.

like image 864
Booger Avatar asked Jan 24 '12 17:01

Booger


People also ask

How to use SpannableString in Android?

All these classes extend the Spanned interface. SpannableString and SpannableStringBuilder also extend the Spannable interface. In order to use a span, we need to call setSpan(Object spans, int start, int end, int flag) on the Spannable object.

What is Spannable in Android?

Spannable. This is the interface for text to which markup objects can be attached and detached. SpannableString. This is the class for text whose content is immutable but to which markup objects can be attached and detached.

How do I align text in text view?

To align text in TextView at the center vertically and horizontally we need to make use of gravity attribute. Example 1 : You can use center_vertical | center_horizontal value to set the text at the center of the TextView area.


1 Answers

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);
    }
}
like image 155
Booger Avatar answered Nov 12 '22 08:11

Booger