String contet= "為了讓您更好的使用本軟件,請(qǐng)充分閱讀并理解《隱私政策》與《使用條款》忙厌。";
tv_content.setText(updateTextStyle(content));
//添加這句話妹蔽,否則點(diǎn)擊不生效
tv_content.setMovementMethod(LinkMovementMethod.getInstance());
private SpannableStringBuilder updateTextStyle(String content) {
SpannableStringBuilder spannableString = new SpannableStringBuilder();
spannableString.append(content);
//使用ForegroundColorSpan添加點(diǎn)擊事件會(huì)出現(xiàn)沖突
UnderlineSpan colorSpan = new UnderlineSpan() {
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.parseColor("#fe9500"));//設(shè)置顏色
}
};
//使用UnderlineSpan很好的兼容這個(gè)問題
UnderlineSpan colorSpan1 = new UnderlineSpan() {
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.parseColor("#fe9500"));//設(shè)置顏色
// ds.setUnderlineText(false); //去掉下劃線
}
};
int privacyBeginIndex = content.indexOf("《");
int privacyEndIndex = content.indexOf("》") + 1;
int protocolBeginIndex = content.lastIndexOf("《");
int protocolEndIndex = content.lastIndexOf("》") + 1;
ClickableSpan privacyClickableSpan = new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
Toast.makeText(MainActivity.this, "123", Toast.LENGTH_LONG).show();
}
};
ClickableSpan protocolClickableSpan = new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
Toast.makeText(MainActivity.this, "123", Toast.LENGTH_LONG).show();
}
};
spannableString.setSpan(protocolClickableSpan, protocolBeginIndex, protocolEndIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
spannableString.setSpan(privacyClickableSpan, privacyBeginIndex, privacyEndIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//字體顏色一定要放在點(diǎn)擊事件后面抱怔,不然部分手機(jī)不會(huì)修改顏色
spannableString.setSpan(colorSpan, protocolBeginIndex, protocolEndIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
spannableString.setSpan(colorSpan1, privacyBeginIndex, privacyEndIndex, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
return spannableString;
}