I have the following String RM123.456. I would like to
Many of the provided answers here require you to set a text size scale percentage and guess an offset to account for their mistake in calculating the correct offset or they require you to set multiple spans.
So, to update this question, here's a solution which sets the correct baseline of the superscript and only asks that you provide a text scale percentage for only 1 required span:
class TopAlignSuperscriptSpan(private val textSizeScalePercentage: Float = 0.5f) : MetricAffectingSpan() {
override fun updateDrawState(tp: TextPaint) {
tp.baselineShift += (tp.ascent() * textSizeScalePercentage).toInt()
tp.textSize = tp.textSize * textSizeScalePercentage
}
override fun updateMeasureState(tp: TextPaint) {
updateDrawState(tp)
}
}
You may use this without having to set other spans, like so:
val spannableString = SpannableString("RM123.456")
spannableString.setSpan(TopAlignSuperscriptSpan(0.6f), 0, 2, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE)
myTextView.text = spannableString
"RM" will be 60% of the text size of "123.456" and it's top will be exactly aligned to the top of "123.456"
UPDATE: You shouldn't use this because it is inexact, like every other answer here. Instead, I would suggest calculating the height of each section of the text view and manually setting the y value of each section, like this library does: https://github.com/fabiomsr/MoneyTextView/tree/master/moneytextview/src/main/res/values