Android SpannableStringBuilder改变某部分字体

/**
 * 改变TextView部分字体的颜色
 *
 * @param originalValue 整个字符串
 * @param indexValue 需要改变的字
 * @param color 改变的颜色
 * @return
 */

public static SpannableStringBuilder setTextViewColor(String originalValue, String indexValue, int color) {
    SpannableStringBuilder builder = new SpannableStringBuilder(originalValue);
    if (TextUtils.isEmpty(originalValue)) {
        return builder;
    }
    for (int j = 0; j < originalValue.length(); j++) {
        if (j + indexValue.length() <= originalValue.length()) {
            String name = (String) originalValue.subSequence(j, j + indexValue.length());
            if (name.equals(indexValue)) {
                ForegroundColorSpan redSpan = new ForegroundColorSpan(color);
                builder.setSpan(redSpan, j, j + indexValue.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }
    return builder;
}

 

/**
 * 改变TextView部分字体的颜色和大小
 *
 * @param originalValue 整个字符串
 * @param indexValue 需要改的部分
 * @param color 需要改变的颜色
 * @param size 需要改变的字体大小
 * @param mIsBold 需要改变的字体是否加粗
 * @return
 */
public static SpannableStringBuilder setTextViewColorAndSize(String originalValue, String indexValue, int color, int size, boolean mIsBold) {
    SpannableStringBuilder builder = new SpannableStringBuilder(originalValue);
    if (TextUtils.isEmpty(originalValue)) {
        return builder;
    }
    for (int j = 0; j < originalValue.length(); j++) {
        if (j + indexValue.length() <= originalValue.length()) {
            String name = (String) originalValue.subSequence(j, j + indexValue.length());
            if (name.equals(indexValue)) {
                ForegroundColorSpan redSpan = new ForegroundColorSpan(color);
                builder.setSpan(new AbsoluteSizeSpan(size), j, j + indexValue.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                int typeface;
                if (!mIsBold) {
                    typeface = Typeface.NORMAL;
                } else {
                    typeface = Typeface.BOLD;
                }
                builder.setSpan(new StyleSpan(typeface), j, j + indexValue.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                builder.setSpan(redSpan, j, j + indexValue.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }
    return builder;
}

 

点击链接加入群聊【编程之美】:https://jq.qq.com/?_wv=1027&k=9qYaAE3t

你可能感兴趣的:(Android,Android,Studio)