android – 将ImageSpan对齐到TextView的顶部
作者:互联网
目前,我希望在文本之间添加一个图像,并将其对齐到TextView的顶部.
像这样的东西:
我能找到的唯一垂直对齐是基线(似乎将它放在文本的中心)并对齐底部.
如果我使用ALIGN_BASELINE会发生什么:
有没有办法将它与顶部对齐?
我目前的代码:
txtView.setText(this.addImageAsterisk(
"The string to have asterisk at the end*"), BufferType.SPANNABLE);
然后
private CharSequence addImageAsterisk(String string) {
Drawable d = context.getResources().getDrawable(R.drawable.img_asterisk);
ImageSpan imageSpan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
final SpannableString spannableString = new SpannableString(string);
spannableString.setSpan(imageSpan, string.length()-1, string.length(), 0);
return spannableString;
}
删除ImageSpan.ALIGN_BASELINE将其设置为与底部对齐,这也不是我预期的结果.
—谢谢用户Lalit Poptani,我试着应用你的答案—-
应用这个之后,会发生的是整个textview似乎有额外的余量.
在应用范围之前:
This is the text*
在应用SuperscriptSpanAdjuster之后
(some extra space)
This is the text*
我的代码:
String string = "This is the text*";
Drawable d = this.context.getResources().getDrawable(R.drawable.img_asterisk);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan imageSpan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
SuperscriptSpanAdjuster s = new SuperscriptSpanAdjuster(1.5);
final SpannableString spannableString = new SpannableString(string);
spannableString.setSpan(s, string.length() - 1, string.length(), 0);
spannableString.setSpan(imageSpan, string.length(), string.length() + 1, 0);
textView.setText(spannableString);
解决方法:
您可以做的是使用自定义MetricAffectingSpan来维持其比率,如,
public class SuperscriptSpanAdjuster extends MetricAffectingSpan {
double ratio = 0.5;
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);
}
}
你可以使用SpannableString将星号应用于你的String,就像
SpannableString mString = new SpannableString("This is what I wanted*");
mString.setSpan(new SuperscriptSpanAdjuster(0.5), mString.length() - 1,
mString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
mTextView.append("\n");
mTextView.append(mString);
这会根据您的需要在文本中添加星号.你的输出将是,
标签:android,textview,spannablestring 来源: https://codeday.me/bug/20191006/1860599.html