SpannableString设置不同大小字体顶部对齐
网上复制粘贴就行了
private float sp2px(Context context, float sp) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return sp * scaledDensity;
}
private void setCocoBalance(String balance) {
SpannableString spannableString = new SpannableString("余额 " + balance);
spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), 2, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new AbsoluteSizeSpan(12, true), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new AbsoluteSizeSpan(35, true), 3, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 3, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new TopSpan((int) sp2px(getContext(), 12), Color.parseColor("#4D4D4D")), 0, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tvCocoAmount.setText(spannableString);
}
设置让前两个字符串顶部对齐
public class TopSpan extends ReplacementSpan {
private float fontSizePx;
private int color;
public TopSpan(float fontSizePx,int color) {
this.fontSizePx = fontSizePx;
this.color = color;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
text = text.subSequence(start, end);
Paint p = getCustomTextPaint(paint);
return (int) p.measureText(text.toString());
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
text = text.subSequence(start, end);
Paint p = getCustomTextPaint(paint);
Paint.FontMetricsInt fm = p.getFontMetricsInt();
canvas.drawText(text.toString(), x, y - ((y + fm.descent + y + fm.ascent) - (bottom + top)), p);
}
private TextPaint getCustomTextPaint(Paint srcPaint) {
TextPaint paint = new TextPaint(srcPaint);
paint.setTextSize(fontSizePx);
paint.setColor(color);
return paint;
}
}