1、当前示例中间的 "评论",使用SpannableStringBuilder实现,点击评论会有高亮效果加粗,但再点击其它Bar时无法恢复默认样式。
2、因为SpannableString或SpannableStringBuilder中的效果是叠加的,恢复默认样式需要先移除加粗样式 spannable.removeSpan(样式)。
3、示例代码
// 样式是叠加的,所以要清除之前的样式 spannableStringBuilder.removeSpan(highlightSpanColor);
spannableStringBuilder.removeSpan(highlightSpanStyle);
private SpannableStringBuilder spannableStringBuilder;// 评论 默认样式// 字体颜色ForegroundColorSpan defaultSpanColor = new ForegroundColorSpan(getResources().getColor(com.lstm.baselibrary.R.color.color_606266,null));// 字体大小AbsoluteSizeSpan defaultSpanSize = new AbsoluteSizeSpan(DisplayUtils.dp2px(getContext(), 15));// 字体样式StyleSpan defaultSpanStyle = new StyleSpan(Typeface.NORMAL);// 评论 高亮样式// 字体颜色ForegroundColorSpan highlightSpanColor = new ForegroundColorSpan(getResources().getColor(com.lstm.baselibrary.R.color.color_303133,null));// 字体样式StyleSpan highlightSpanStyle = new StyleSpan(Typeface.BOLD); // 字体加粗// 评论数量 样式// 字体颜色ForegroundColorSpan countColor = new ForegroundColorSpan(getResources().getColor(com.lstm.baselibrary.R.color.color_909399, null));// 字体大小AbsoluteSizeSpan countSize = new AbsoluteSizeSpan(DisplayUtils.dp2px(getContext(), 12));/*** 不同样式拼接 默认样式*/private void splicingDefaultTextStyle() {spannableStringBuilder = new SpannableStringBuilder(getText());// 评论spannableStringBuilder.removeSpan(highlightSpanColor); // 样式是叠加的,所以要清除之前的样式spannableStringBuilder.removeSpan(highlightSpanStyle);spannableStringBuilder.setSpan(defaultSpanColor, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体颜色spannableStringBuilder.setSpan(defaultSpanSize, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体大小spannableStringBuilder.setSpan(defaultSpanStyle, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体样式// 评论数量spannableStringBuilder.setSpan(countColor, 2, getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体颜色spannableStringBuilder.setSpan(countSize, 2, getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体大小spannableStringBuilder.setSpan(defaultSpanStyle, 2, getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体样式setText(spannableStringBuilder);}/*** 不同样式拼接 高亮样式*/private void splicingHighlightTextStyle() {spannableStringBuilder = new SpannableStringBuilder(getText());// 评论spannableStringBuilder.removeSpan(defaultSpanColor); // 样式是叠加的,所以要清除之前的样式spannableStringBuilder.removeSpan(defaultSpanStyle);spannableStringBuilder.setSpan(highlightSpanColor, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体颜色spannableStringBuilder.setSpan(defaultSpanSize, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体大小spannableStringBuilder.setSpan(highlightSpanStyle, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体样式// 评论数量spannableStringBuilder.setSpan(countColor, 2, getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体颜色spannableStringBuilder.setSpan(countSize, 2, getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体大小spannableStringBuilder.setSpan(defaultSpanStyle, 2, getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); // 字体样式setText(spannableStringBuilder);}