標籤:Androidjava
咱們常常會遇到一種情景,就是一行文字,卻有不一樣的字體或不一樣的顏色,好比這樣:
android
通常來講,有三種方案來實現:多個TextView、使用Html標籤、使用Spannableapp
這裏,Html標籤的方式在不一樣字體時很差處理,能夠忽略。而多個TextView的方式呢,會增長視圖的個數,有點low。字體
可是,Spannable這個玩意呢,雖然看起來無所不能,可是使用起來真是麻煩的一逼,文本的下標一不當心搞錯了就會出錯。因此呢,我對Spannable作了一下簡單的封裝,方便快速使用。目前僅支持同一個TextView顯示不一樣字體、不一樣顏色。ui
tvTitle.setText(SpannableBuilder.create(this) .append("關聯店鋪", R.dimen.sp16, R.color.text_33) .append("(請添加您的全部店鋪)", R.dimen.sp12, R.color.text_99) .build());
import android.content.Context; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.AbsoluteSizeSpan; import android.text.style.ForegroundColorSpan; import java.util.ArrayList; import java.util.List; /** * 做者:餘自然 on 2017/2/22 下午4:06 */ public class SpannableBuilder { private Context context; private List<SpanWrapper> list; private SpannableBuilder(Context context) { this.context = context; this.list = new ArrayList<>(); } public SpannableBuilder append(String text, int textSize, int textColor) { list.add(new SpanWrapper(text, textSize, textColor)); return this; } public Spannable build() { SpannableStringBuilder textSpan = new SpannableStringBuilder(); int start = 0; int end = 0; for (int i = 0; i < list.size(); i++) { SpanWrapper wrapper = list.get(i); String text = wrapper.getText(); start = end; end = end + text.length(); textSpan.append(text); AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(getContext().getResources().getDimensionPixelSize(wrapper.getTextSize())); ForegroundColorSpan colorSpan = new ForegroundColorSpan(getContext().getResources().getColor(wrapper.getTextColor())); textSpan.setSpan(sizeSpan, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); textSpan.setSpan(colorSpan, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); } return textSpan; } public static SpannableBuilder create(Context context) { return new SpannableBuilder(context); } public Context getContext() { return context; } private class SpanWrapper { String text; int textSize; int textColor; public SpanWrapper(String text, int textSize, int textColor) { this.text = text; this.textSize = textSize; this.textColor = textColor; } public String getText() { return text; } public void setText(String text) { this.text = text; } public int getTextSize() { return textSize; } public void setTextSize(int textSize) { this.textSize = textSize; } public int getTextColor() { return textColor; } public void setTextColor(int textColor) { this.textColor = textColor; } } }