使用SpannableString设置同一个textView不同样式和置顶

下面这个是SpannableString的用法,很简单

rivate 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);
        //设置字体大小,true表示前面的字体大小20单位为dip
        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);
        //设置字体,BOLD为粗体
        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);
    }

TopSpan是顶部对齐的工具类,直接复制粘贴就可以

/**
 * 使TextView中不同大小字体顶部对齐
 */
public class TopSpan extends ReplacementSpan {

    private float fontSizePx;    //px
    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();
        // 此处重新计算y坐标,使字体顶部对齐
        canvas.drawText(text.toString(), x, y - ((y + fm.descent + y + fm.ascent) - (bottom + top)), p);
//        canvas.drawText(text.toString(), x, y, p);
    }

    private TextPaint getCustomTextPaint(Paint srcPaint) {
        TextPaint paint = new TextPaint(srcPaint);
        paint.setTextSize(fontSizePx);   //设定字体大小, sp转换为px
        paint.setColor(color);
        return paint;
    }
}

下面是用kotlin设置的,只是设置了textview的大小。并没有多做样式,不过方法是一样

rb_liveAlert.text = SpannableStringBuilder().apply {
            append(getString(R.string.liveDetailLiveTab_liveAlert))
            append(liveDetailInfo.rnum_tab ?: "", AbsoluteSizeSpan(sp(11)))

        }

 

你可能感兴趣的:(Android)