/** * 改变TextView部分字体的颜色 * * @param originalValue 整个字符串 * @param indexValue 需要改变的字 * @param color 改变的颜色
* @return */
//单个字体改变颜色并添加点击事件
public static SpannableStringBuilder setTextViewColor(Activity mActivity,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(new ClickableSpan() { @Override public void onClick(@NonNull View widget) { //实现逻辑 } @Override public void updateDrawState(@NonNull TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false);//去掉下划线 } }, j, j + indexValue.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); builder.setSpan(redSpan, j, j + indexValue.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } return builder; }
切记要加上这句 不然点击事件不起作用 切记 切记 切记 重要的事要说一百遍
view表示你要给那个控件设置
view.setMovementMethod(LinkMovementMethod.getInstance());
/**
* 改变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