1、ClickableSpan的使用
下面方法給字元串中數字添加點選事件:
private SpannableString spannableText(String text){
if(TextUtils.isEmpty(text)){
return SpannableString.valueOf("");
}
Pattern p = Pattern.compile("(120)|(110)|(119)|(122)|(114)|(121)|(999)|([0-9]{5,13})");
Matcher m = p.matcher(text);
SpannableString temp = new SpannableString(text);
int textColor = getResources().getColor(R.color.colorTheme);
while (m.find()){
int start = m.start();
int end = m.end();
String tel = m.group();
ForegroundColorSpan colorSpan = new ForegroundColorSpan(textColor);
temp.setSpan(colorSpan,start,end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
dialPhone(tel);
}
@Override
public void updateDrawState(@NonNull TextPaint ds) {
ds.setUnderlineText(true);
}
};
temp.setSpan(clickableSpan,start,end,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return temp;
}
2、問題
例如,字元串是“姓名:張三\r\n電話:11111111111\r\n性别:男\r\n親屬電話:22222222222”。
問題:使用上面方法添加點選事件後,會發現點選數字後的空白地方,也會執行點選事件。
解決方法:在可能出現空白區域的字元串後添加一個空格字元“\u3000”,即可解決問題。
例如,上面字元串修改後即是:“姓名:張三\r\n電話:11111111111\u3000\r\n性别:男\r\n親屬電話:22222222222\u3000”