(kotlin代碼)java
var builder = SpannableStringBuilder()
複製代碼
SpannableStringUtils.addTextSizeToMsg(builder,"¥",1f)
SpannableStringUtils.addTextSizeToMsg(builder,"2980",1.5f)
SpannableStringUtils.addTextSizeToMsg(builder,".00",1f)
coursePrice.text = builder //把builderset進text中,至關於java的 textView.setText()
複製代碼
最終效果bash
SpannableStringUtils.addTextSizeToMsg(builder,"¥",1f)
SpannableStringUtils.addColorTextToMsg(getColor(R.color.black),builder,"10000")
SpannableStringUtils.addTextSizeToMsg(builder,".00",1f)
複製代碼
SpannableStringUtils.addTextSizeToMsg(builder,"¥",1f)
SpannableStringUtils.addColorTextWithClickEvent(resources.getColor(R.color.xn_blue),builder,"10000",{
Toast.makeText(applicationContext,"show toast",Toast.LENGTH_LONG).show()
})
SpannableStringUtils.addTextSizeToMsg(builder,".00",1f)
複製代碼
點擊下面效果圖藍色部分則能夠彈出toast: app
textView.setMovementMethod(LinkMovementMethod.getInstance())//假如須要設置部分文字可點擊的話必須添加此行設置代碼
textView.setText(builder);
複製代碼
下面是對應的工具類你們複製便可ide
/**
* Created by zhou on 2017/5/22.
*/
public class SpannableStringUtils {
//添加指定顏色的文字到spannable中
public static void addColorTextToMsg(int color, SpannableStringBuilder spsBuilder, String content){
SpannableString contentSps = new SpannableString(content);
contentSps.setSpan(new ForegroundColorSpan(color), 0,content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spsBuilder.append(contentSps);
}
/**
* 字符串變色方法,簡潔版
* @param color 要變成的顏色
* @param colorStr 要變色的字符串
* @param endStr 不變色的字符串
* @return
*/
public static SpannableStringBuilder addColorToText(int color,String colorStr,String endStr){
SpannableStringBuilder builder = new SpannableStringBuilder();
addColorTextToMsg(color,builder,colorStr);
builder.append(endStr);
return builder;
}
//添加指定顏色指定大小的文字到spannable中
public static void addTextSizeToMsg(SpannableStringBuilder spsBuilder, String content, float size){
SpannableString contentSps = new SpannableString(content);
contentSps.setSpan(new RelativeSizeSpan(size), 0,content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spsBuilder.append(contentSps);
}
public static void addColorTextWithClickEvent(final int color, SpannableStringBuilder spsBuilder, String content, final OnTextClickListener onTextClickListener){
SpannableString contentSps = new SpannableString(content);
// contentSps.setSpan(new ForegroundColorSpan(color), 0,content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
contentSps.setSpan(new ClickableSpan() {
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(color);
ds.setUnderlineText(false); //設置下劃線
}
@Override
public void onClick(View widget) {
onTextClickListener.onClick();
}
}, 0,content.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spsBuilder.append(contentSps);
}
public interface OnTextClickListener{
void onClick();
}
}
複製代碼