TextView的SpanableString的坑:不能多次setSpan的解决方案

原方法要实现的效果是将“XX月XX日”的“月”和“日”设置成不同样式,包括颜色、字体大小和加粗/不加粗。

private void setDateText(String dateStr) {
        if (TextUtils.isEmpty(dateStr)) {
            this.keywords.setVisibility(View.INVISIBLE);
            return;
        }
        this.keywords.setVisibility(View.VISIBLE);
        if (Pattern.matches("\\d{1,2}月\\d{1,2}日.*", dateStr)) {
            int monthIndex = dateStr.indexOf("月");
            int dayIndex = dateStr.indexOf("日");
            RelativeSizeSpan sizeSpan = new RelativeSizeSpan(0.612f);
            StyleSpan fontSpan = new StyleSpan(Typeface.NORMAL);
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(
                ContextCompat.getColor(keywords.getContext(), R.color.color_999999));
            this.keywords.setText(
                getSpannableDate(dateStr, monthIndex, dayIndex, sizeSpan, fontSpan, colorSpan));
        } else {
            this.keywords.setText(dateStr);
        }
    }

private SpannableStringBuilder getSpannableDate(String dateStr, int monthIndex, int dayIndex,
        ParcelableSpan... spans) {
        
        SpannableStringBuilder spannable = new SpannableStringBuilder(dateStr);
        for (ParcelableSpan ps : spans) {
            spannable.setSpan(ps, monthIndex, monthIndex + 1,
                Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            spannable.setSpan(ps, dayIndex, dayIndex + 1,
                Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }
        return spannable;
    }

结果只有后面的“日”设置成了目标样式,“月”没变。
解决方案:感谢https://blog.csdn.net/gxp1182893781/article/details/76916796给出的提示:使用CharacterStyle.wrap()方法,getSpannableDate()修改成如下:

private SpannableStringBuilder getSpannableDate(String dateStr, int monthIndex, int dayIndex,
        CharacterStyle... styles) {
        SpannableStringBuilder spannable = new SpannableStringBuilder(dateStr);
        for (CharacterStyle cs : styles) {
            spannable.setSpan(CharacterStyle.wrap(cs), monthIndex, monthIndex + 1,
                Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            spannable.setSpan(CharacterStyle.wrap(cs), dayIndex, dayIndex + 1,
                Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }
        return spannable;
    }

OK了!

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