今天在寫項目的時候碰到了一個TextView的需求,它長這個樣子
看到之後最簡單的就是寫兩個TextView
或者通過Html標籤搞定
今天我們換一種方式,使用系統的 SpannableStringBuilder搞定
話不多說,上代碼
第一種簡單的實現樣式
Kotlin寫法,項目其他地方用法 上來補充
var span = SpannableString("已生成二維碼,點擊保存")
span.setSpan(ForegroundColorSpan(Color.parseColor("#DB6579")), span.length - 4, span.length, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
message_new_count_tv.text = span
Java寫法
SpannableString span=new SpannableString("已生成二維碼,點擊保存");
span.setSpan(new ForegroundColorSpan(Color.parseColor("#DB6579")), span.length - 4, span.length, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
message_new_count_tv.setText(span);
第二種帶上點擊事件
String str = "已生成二維碼,點擊保存";
//這個是爲了設置點擊後 文字變色情況
qr_code_onclick_tv.setHighlightColor(getResources().getColor(android.R.color.transparent));
SpannableStringBuilder style = new SpannableStringBuilder(str);
//設置部分文字點擊事件
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(QRCodeActivity.this, "觸發點擊事件!", Toast.LENGTH_SHORT).show();
((TextView) widget).setHighlightColor(getResources().getColor(android.R.color.transparent));
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);//用於設置你的文字什麼顏色
ds.setColor(Color.parseColor("#DB6579"));
ds.setUnderlineText(false);
ds.clearShadowLayer();
}
};
style.setSpan(clickableSpan, str.length() - 4, str.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
qr_code_onclick_tv.setText(style);
qr_code_onclick_tv.setMovementMethod(LinkMovementMethod.getInstance());
複雜一點,可以設置背景和圖片的請跳轉鏈接
好了試一下效果吧!