目前,我希望在文本之间添加一个图像并将其与 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
将星号应用于您的字符串,例如,
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 - 将 ImageSpan 对齐到 TextView 的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20392218/