Android Span在项目中的几种使用方式

  • 1.字符串中 改变字体颜色和大小
  • 2.字符串中 改变文字颜色 并 添加点击事件
  • 3.字符串中 增加外框和改变文字颜色及字体大小

1.改变文字颜色

ForegroundColorSpan

/**
 * 自定义颜色
 *
 * @param content 全部文本
 * @param keyWord 需要变色的关键字
 * @param color   颜色
 */
public static SpannableStringBuilder getSpan(String content, String keyWord, int color) {
    SpannableStringBuilder span = null;
    if (content == null) {
        span = new SpannableStringBuilder("");
        return span;
    } else {
        int startIndex = 0;
        int endIndex = 0;
        if (keyWord != null) {
            startIndex = content.indexOf(keyWord);
            endIndex = content.indexOf(keyWord) + keyWord.length();
            span = new SpannableStringBuilder(content);
            if (startIndex != -1 && startIndex <= endIndex) {
                span.setSpan(new ForegroundColorSpan(getResoure().getColor(color)), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return span;
    }
}

1.改变文字大小

AbsoluteSizeSpan

/**
 * 设置单个字符串的文字大小
 *
 * @param content 全部文字
 * @param keyWord 需要改变的文本
 * @param spValue 需要设置的文本大小
 */
public static SpannableStringBuilder getSizeSpan(String content, String keyWord, float spValue) {
    SpannableStringBuilder span = null;
    if (TextUtils.isEmpty(content)) {
        span = new SpannableStringBuilder("");
        return span;
    } else {
        int startIndex = 0;
        int endIndex = 0;
        if (keyWord != null) {
            startIndex = content.indexOf(keyWord);
            endIndex = content.indexOf(keyWord) + keyWord.length();
            span = new SpannableStringBuilder(content);
            if (startIndex != -1 && startIndex <= endIndex) {
                float px = DensityAppUtil.sp2px(spValue);
                span.setSpan(new AbsoluteSizeSpan((int) px), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return span;
    }
}

3.改变文字颜色 并 添加点击事件

ClickableSpan

public class ButtonSpan extends ClickableSpan {

    View.OnClickListener onClickListener;
    private Context context;
    private int colorId;

    public ButtonSpan(Context context, View.OnClickListener onClickListener) {
        this(context, onClickListener, R.color.color_theme);
    }

    public ButtonSpan(Context context, View.OnClickListener onClickListener, int colorId) {
        this.onClickListener = onClickListener;
        this.context = context;
        this.colorId = colorId;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        ds.setColor(context.getResources().getColor(colorId));
        ds.setUnderlineText(false);
    }

    @Override
    public void onClick(View widget) {
        if (onClickListener != null) {
            onClickListener.onClick(widget);
        }
    }
}

设置:

// content为全部的字符串,keyWord为需要改变的字符串
SpannableString spannableString = new SpannableString(content);
ButtonSpan span = new ButtonSpan(v.getContext(), new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // do something..
        }
    }
}, R.color.color_theme);
spannableString.setSpan(span, content.indexOf(keyWord), content.indexOf(keyWord + keyWord.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//不设置 没有点击事件
titleTop.setMovementMethod(LinkMovementMethod.getInstance());
//设置点击后的颜色为透明
titleTop.setHighlightColor(Color.TRANSPARENT);
titleTop.setText(spannableString);

4.增加边框和改变颜色及字体大小

ReplacementSpan

public class TagSpan extends ReplacementSpan {

    // span width
    private int mSize;
    // text and background wireframe color
    private int mColor;
    // tag text size
    private int mTextSizePx;
    // background radius
    private int mRadiusPx;
    // background wireframe right margin
    private int mRightMarginPx;

    public TagSpan(int color, int textSizePx, int radiusPx, int rightMarginPx) {
        mColor = color;
        mTextSizePx = textSizePx;
        mRadiusPx = radiusPx;
        mRightMarginPx = rightMarginPx;
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        mSize = (int) paint.measureText(text, start, end) + mRightMarginPx;
        return mSize;
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        drawTagRect(canvas, x, y, paint);
        drawTagText(canvas, text, start, end, y, paint);
    }

    private void drawTagRect(Canvas canvas, float x, int y, Paint paint) {
        paint.setColor(mColor);
        paint.setAntiAlias(true);

        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        final float strokeWidth = paint.getStrokeWidth();
        RectF oval = new RectF(x + strokeWidth + 0.5f, y + fontMetrics.ascent, x + mSize + strokeWidth + 0.5f - mRightMarginPx, y + fontMetrics.descent);
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawRoundRect(oval, mRadiusPx, mRadiusPx, paint);
    }

    private void drawTagText(Canvas canvas, CharSequence text, int start, int end, int y, Paint paint) {
        paint.setTextSize(mTextSizePx);
        paint.setColor(mColor);
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.CENTER);

        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        final int textCenterX = (mSize - mRightMarginPx / 2) / 2;
        int textBaselineY = (int) (y - fontMetrics.descent / 2);
        final String tag = text.subSequence(start, end).toString();
        canvas.drawText(tag, textCenterX, textBaselineY, paint);
    }
}

调用静态方法:

/**
 * 增加边框和改变颜色及字体大小
 *
 * @param content 内容
 * @param keyWord 关键字
 * @param color   颜色
 * @param sp      字体sp,需转换为对应的px
 */
public static SpannableStringBuilder getSpan(String content, String keyWord, int color, int sp) {
    SpannableStringBuilder span = null;
    if (content == null) {
        span = new SpannableStringBuilder("");
        return span;
    } else {
        int startIndex = 0;
        int endIndex = 0;

        if (!TextUtils.isEmpty(keyWord)) {
            startIndex = content.indexOf(keyWord);
            endIndex = content.indexOf(keyWord) + keyWord.length();
            span = new SpannableStringBuilder(content);
            if (startIndex != -1 && startIndex <= endIndex) {
                // 圆角 右边距
                span.setSpan(new TagSpan(color, (int) sp, 4, 8), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return span;
    }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券