項(xiàng)目中遇到一個(gè)需求,需要在商品標(biāo)題加上標(biāo)簽,而標(biāo)簽是客戶可以后臺(tái)配置的,所以不是用的圖片,而是用的文字.如下圖:
眾所周知,在Android中,View都是呈方形布置的,所以如果標(biāo)簽和文字如果不是同一個(gè)View,那么如果文字換行,就會(huì)出現(xiàn)標(biāo)簽和TextView分別在左右兩邊的效果:
經(jīng)過思考和查閱資料,發(fā)現(xiàn)可以用SpannableString設(shè)置背景,并通過重寫ReplacementSpan替換原來的BackgroundColorSpan來實(shí)現(xiàn)圓角標(biāo)簽.
下面是代碼:
Activity: (goodsTags為標(biāo)簽文字集合,即上圖的"促","九","八"...goodsName為商品名字
for (int i = 0; i < goodsTags.size(); i++) {
//為了顯示效果在每個(gè)標(biāo)簽文字前加兩個(gè)空格,后面加三個(gè)空格(前兩個(gè)和后兩個(gè)填充背景,最后一個(gè)作標(biāo)簽分割)
goodsName.insert(0, " " + goodsTags.get(i).getTags_name() + " ");
int start = 0;
int end = 5;
//稍微設(shè)置標(biāo)簽文字小一點(diǎn)
goodsName.setSpan(new RelativeSizeSpan(0.9f), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//設(shè)置圓角背景
goodsName.setSpan(new RoundBackgroundColorSpan(Color.parseColor("#" + goodsTags.get(i).getTags_color()),Color.WHITE), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
自定義RoundBackgroundColorSpan:
public class RoundBackgroundColorSpan extends ReplacementSpan {
private int bgColor;
private int textColor;
public RoundBackgroundColorSpan(int bgColor, int textColor) {
super();
this.bgColor = bgColor;
this.textColor = textColor;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
//設(shè)置寬度為文字寬度加16dp
return ((int)paint.measureText(text, start, end)+Util.px2Dp(16));
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
int originalColor = paint.getColor();
paint.setColor(this.bgColor);
//畫圓角矩形背景
canvas.drawRoundRect(new RectF(x,
top+ Util.px2Dp(3),
x + ((int) paint.measureText(text, start, end)+ Util.px2Dp(16)),
bottom-Util.px2Dp(1)),
Util.px2Dp(4),
Util.px2Dp(4),
paint);
paint.setColor(this.textColor);
//畫文字,兩邊各增加8dp
canvas.drawText(text, start, end, x+Util.px2Dp(8), y, paint);
//將paint復(fù)原
paint.setColor(originalColor);
}
}