Android Spannable为同一TextView设直不同样式

   /**
     * UNICODE
     * <p>
     * 偶尔吃(1~2次/周)   (   中文破弧
     * 经常吃(3~5次/周)    (    英文破弧
     *
     * @param name
     * @return
     */
    private Spannable formatName(String name) {
        if (name.contains(STRING_TYPE_CN)) {
            return changeStringStyle(STRING_TYPE_CN, name, "\\(");
        } else if (name.contains(STRING_TYPE_EN)) {
            return changeStringStyle(STRING_TYPE_EN, name, "\\(");
        } else {
            return new SpannableString(name);
        }
    }

    private Spannable changeStringStyle(String type, String name, String splitRegex) {
        StringBuilder skr = new StringBuilder();
        String[] split = name.split(splitRegex);
        if (split.length == 2) {
            //改变字体大小、颜色、加换行
            split[1] = type + split[1];
            skr.append(split[0]).append("\r\n").append(split[1]);
            Spannable span = new SpannableString(skr.toString());
            //设置字体大小(绝对值,单位:像素)
            span.setSpan(new AbsoluteSizeSpan(this.mHintTextSize), split[0].length(), skr.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            //设置字体颜色
            span.setSpan(new ForegroundColorSpan(this.mHintTextColor), split[0].length(), skr.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            return span;
        }
        return new SpannableString(name);
    }

参考:http://hunankeda110.iteye.com/blog/1420470

猜你喜欢

转载自www.cnblogs.com/jooy/p/10039631.html