如何使 RelativeSizeSpan 对齐到顶部 [英] How to make RelativeSizeSpan align to top
本文介绍了如何使 RelativeSizeSpan 对齐到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字符串 RM123.456.我愿意
I have the following String RM123.456. I would like to
- 使RM相对较小
- 使 RM 与顶部完全对齐
- Make RM relatively smaller
- Make RM aligned to top exactly
我几乎可以通过使用来实现
I almost able to achieve it by using
spannableString.setSpan(new RelativeSizeSpan(0.50f), 0, index, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString, TextView.BufferType.SPANNABLE);
结果看起来像
然而,它是对齐到底部的.它不与顶部对齐.
However, it is aligned to the bottom. It doesn't align to the top.
我尝试使用 SuperscriptSpan
.看起来像
I try to use SuperscriptSpan
. It looks like
它没有做我想要的
SuperscriptSpan
不会使文本变小.我无法控制它的大小.SuperscriptSpan
将使文本在顶部对齐"
SuperscriptSpan
doesn't make the text smaller. I'm not able to control its sizing.SuperscriptSpan
will make the text "over the top align"
我可以知道,我怎样才能让 RelativeSizeSpan 准确地对齐到顶部?
May I know, how can I make RelativeSizeSpan align to top exactly?
这就是我想要的.
请注意,我们不希望采用 2 TextViews 解决方案.
推荐答案
然而我是这样做的:
activity_main.xml:
<TextView
android:id="@+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:textSize="26sp" />
MainActivity.java:
TextView txtView = (TextView) findViewById(R.id.txtView);
SpannableString spannableString = new SpannableString("RM123.456");
spannableString.setSpan( new TopAlignSuperscriptSpan( (float)0.35 ), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
txtView.setText(spannableString);
TopAlignSuperscriptSpan.java:
private class TopAlignSuperscriptSpan extends SuperscriptSpan {
//divide superscript by this number
protected int fontScale = 2;
//shift value, 0 to 1.0
protected float shiftPercentage = 0;
//doesn't shift
TopAlignSuperscriptSpan() {}
//sets the shift percentage
TopAlignSuperscriptSpan( float shiftPercentage ) {
if( shiftPercentage > 0.0 && shiftPercentage < 1.0 )
this.shiftPercentage = shiftPercentage;
}
@Override
public void updateDrawState( TextPaint tp ) {
//original ascent
float ascent = tp.ascent();
//scale down the font
tp.setTextSize( tp.getTextSize() / fontScale );
//get the new font ascent
float newAscent = tp.getFontMetrics().ascent;
//move baseline to top of old font, then move down size of new font
//adjust for errors with shift percentage
tp.baselineShift += ( ascent - ascent * shiftPercentage )
- (newAscent - newAscent * shiftPercentage );
}
@Override
public void updateMeasureState( TextPaint tp ) {
updateDrawState( tp );
}
}
希望对你有帮助.
这篇关于如何使 RelativeSizeSpan 对齐到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文