開(kāi)發(fā)工具類型的App猬腰,多少都會(huì)碰到鏈接、電話猜敢、郵箱等地址跳轉(zhuǎn)問(wèn)題姑荷,TextView中的autolink屬性可以自動(dòng)識(shí)別鏈接、手機(jī)號(hào)缩擂、郵箱...鼠冕,只要一行代碼即可實(shí)現(xiàn)。
android:autoLink="all"
但是自帶的文字樣式可能滿足我們的需求胯盯,那么我們可以把目光移向“URLSpan”懈费、“ClickableSpan”
只需要繼承ClickableSpan并重寫(xiě)“updateDrawState”方法即可改變樣式
方法
public class PhoneSpan extends URLSpan {
public PhoneSpan(String url) {
super(url);
}
@Override
public void updateDrawState(TextPaint ds) {
//設(shè)置字體顏色
ds.setColor(Color.parseColor("#3598db"));
//去掉下劃線
ds.setUnderlineText(false);
}
}
使用 android:autoLink="web|phone"
的控制臺(tái)日志
使用
CharSequence content = textView.getText();
if (content instanceof Spannable) {
int end = text.length();
Spannable sp = (Spannable) content;
URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(content );
spannableStringBuilder.clearSpans();
for (URLSpan urlSpan : urls) {
if(url.startsWith("tel:")){
PhoneSpan phoneSpan = new PhoneSpan (urlSpan.getURL());
spannableStringBuilder.setSpan(phoneSpan , sp.getSpanStart(urlSpan), sp.getSpanEnd(urlSpan),
Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
}
textView.setText(spannableStringBuilder);
}
那么你在設(shè)置這個(gè)Autolink的時(shí)候,如果你在TextView上設(shè)置了長(zhǎng)按監(jiān)聽(tīng)博脑,那么就會(huì)出現(xiàn)TextView的長(zhǎng)按事件響應(yīng)了憎乙,同時(shí)當(dāng)你觸摸離開(kāi)屏幕也就是觸發(fā)了“MotionEvent.ACTION_UP”,同時(shí)你也會(huì)發(fā)現(xiàn)ClickableSpan點(diǎn)擊事件也響應(yīng)了,如果不相信這個(gè)你可以自己搞個(gè)demo試試叉趣。
解決方案就是重寫(xiě)LinkMovementMethod
中的onTouchEvent
方法
public class LinkMovementClickMethod extends LinkMovementMethod {
private long lastClickTime;
private static final long CLICK_DELAY = 500L;
public static LinkMovementClickMethod getInstance() {
if (null == sInstance) {
sInstance = new LinkMovementClickMethod();
}
return sInstance;
}
private static LinkMovementClickMethod sInstance;
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_DOWN) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
if (System.currentTimeMillis() - lastClickTime < CLICK_DELAY) {
link[0].onClick(widget);
}
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
lastClickTime = System.currentTimeMillis();
}
return true;
} else {
Selection.removeSelection(buffer);
}
}
return super.onTouchEvent(widget, buffer, event);
}
}
明年會(huì)更好