Android Spannable為同一TextView設直不同樣式
阿新 • • 發佈:2018-11-29
/** * 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