TextView AutoLink, ClikSpan 与长按事件冲突的解决

autolink 的 onclick 事件是在哪里响应的

首先我们需要查找 mAutoLinkMask 在 TextView 哪些地方被调用,很快,我们发现在 setText 里面使用了 mAutoLinkMask

private void setText(CharSequence text, BufferType type,

boolean notifyBefore, int oldlen) {


if (mAutoLinkMask != 0) {

Spannable s2;

if (type == BufferType.EDITABLE || text instanceof Spannable) {

s2 = (Spannable) text;

} else {

s2 = mSpannableFactory.newSpannable(text);

}

if (Linkify.addLinks(s2, mAutoLinkMask)) {

text = s2;

type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;

/*

  • We must go ahead and set the text before changing the

  • movement method, because setMovementMethod() may call

  • setText() again to try to upgrade the buffer type.

*/

setTextInternal(text);

// Do not change the movement method for text that support text selection as it

// would prevent an arbitrary cursor displacement.

if (mLinksClickable && !textCanBeSelected()) {

setMovementMethod(LinkMovementMethod.getInstance());

}

}

}

  • 首先调用 Linkify.addLinks 方法解析 autolink 的相关属性

  • 判断是否 mLinksClickable mLinksClickable && !textCanBeSelected() ,若返回 true, 设置 setMovementMethod

我们先来看一下 Linkify 类, 里面定义了几个常量, 分别对应 web , email ,phone ,map,他们的值是位上错开的,这样定义的好处是

  • 方便组合多种值

  • 组合值之后不会丢失状态,即可以获取是否含有某种状态, web, email, phone , map

public class Linkify {

public static final int WEB_URLS = 0x01;

public static final int EMAIL_ADDRESSES = 0x02;

public static final int PHONE_NUMBERS = 0x04;

public static final int MAP_ADDRESSES = 0x08;

}

看一下 linkify 的 addLinks 方法

  • 根据 mask 的标志位,进行相应的正则表达式进行匹配,找到 text 里面的相应的 WEB_URLS, EMAIL_ADDRESSES, PHONE_NUMBERS, MAP_ADDRESSES. 并将相应的文本从 text 里面移除,封装成 LinkSpec,并添加到 links 里面

  • 遍历 links,设置相应的 URLSpan

private static boolean addLinks(@NonNull Spannable text, @LinkifyMask int mask,

@Nullable Context context) {

if (mask == 0) {

return false;

}

URLSpan[] old = text.getSpans(0, text.length(), URLSpan.class);

for (int i = old.length - 1; i >= 0; i–) {

text.removeSpan(old[i]);

}

ArrayList links = new ArrayList();

/ / 根据正则表达式提取 text 里面相应的 WEB_URLS,并且从 text 移除

if ((mask & WEB_URLS) != 0) {

gatherLinks(links, text, Patterns.AUTOLINK_WEB_URL,

new String[] { “http://”, “https://”, “rtsp://” },

sUrlMatchFilter, null);

}

if ((mask & EMAIL_ADDRESSES) != 0) {

gatherLinks(links, text, Patterns.AUTOLINK_EMAIL_ADDRESS,

new String[] { “mailto:” },

null, null);

}

if ((mask & PHONE_NUMBERS) != 0) {

gatherTelLinks(links, text, context);

}

if ((mask & MAP_ADDRESSES) != 0) {

gatherMapLinks(links, text);

}

pruneOverlaps(links);

if (links.size() == 0) {

return false;

}

// 遍历 links,设置相应的 URLSpan

for (LinkSpec link: links) {

applyLink(link.url, link.start, link.end, text);

}

return true;

}

private static final void applyLink(String url, int start, int end, Spannable text) {

URLSpan span = new URLSpan(url);

text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

}

接下来我们一起来看一下这个 URLSpan 是何方神圣,它继承了 ClickableSpan(注意下文会用到它),并且重写了 onClick 方法,我们可以看到在 onClick 方法里面,他通过相应的 intent 取启动相应的 activity。因此,我们可以断定 autolink 的自动跳转是在这里处理的。

public class URLSpan extends ClickableSpan implements ParcelableSpan {

private final String mURL;

/**

  • Constructs a {@link URLSpan} from a url string.

  • @param url the url string

*/

public URLSpan(String url) {

mURL = url;

}

/**

  • Constructs a {@link URLSpan} from a parcel.

*/

public URLSpan(@NonNull Parcel src) {

mURL = src.readString();

}

@Override

public int getSpanTypeId() {

return getSpanTypeIdInternal();

}


@Override

public void onClick(View widget) {

Uri uri = Uri.parse(getURL());

Context context = widget.getContext();

Intent intent = new Intent(Intent.ACTION_VIEW, uri);

intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());

try {

context.startActivity(intent);

} catch (ActivityNotFoundException e) {

Log.w(“URLSpan”, "Actvity was not found for intent, " + intent.toString());

}

}

}

解决了 autolink 属性点击事件在哪里响应了,接下来我们一起看一下 URLSpan 的 onClick 方法是在哪里调用的。

autolink 的 onclick 事件是在哪里被调用的

我们先来复习一下 View 的事件分发机制:

  • dispatchTouchEvent ,这个方法主要是用来分发事件的

  • onInterceptTouchEvent,这个方法主要是用来拦截事件的(需要注意的是ViewGroup才有这个方法,- View没有onInterceptTouchEvent这个方法

  • onTouchEvent 这个方法主要是用来处理事件的

requestDisallowInterceptTouchEvent(true),这个方法能够影响父View是否拦截事件,true 表示父 View 不拦截事件,false 表示父 View 拦截事件

因此我们猜测 URLSpan 的 onClick 事件是在 TextView 的 onTouchEvent 事件里面调用的。下面让我们一起来看一下 TextView 的 onTouchEvent 方法

@Override

public boolean onTouchEvent(MotionEvent event) {

final int action = event.getActionMasked();

if (mEditor != null) {

mEditor.onTouchEvent(event);

if (mEditor.mSelectionModifierCursorController != null

&& mEditor.mSelectionModifierCursorController.isDragAcceleratorActive()) {

return true;

}

}

final boolean superResult = super.onTouchEvent(event);

/*

  • Don’t handle the release after a long press, because it will move the selection away from

  • whatever the menu action was trying to affect. If the long press should have triggered an

  • insertion action mode, we can now actually show it.

*/

if (mEditor != null && mEditor.mDiscardNextActionUp && action == MotionEvent.ACTION_UP) {

mEditor.mDiscardNextActionUp = false;

if (mEditor.mIsInsertionActionModeStartPending) {

mEditor.startInsertionActionMode();

mEditor.mIsInsertionActionModeStartPending = false;

}

return superResult;

}

final boolean touchIsFinished = (action == MotionEvent.ACTION_UP)

&& (mEditor == null || !mEditor.mIgnoreActionUpEvent) && isFocused();

if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()

&& mText instanceof Spannable && mLayout != null) {

boolean handled = false;

if (mMovement != null) {

handled |= mMovement.onTouchEvent(this, mSpannable, event);

}

final boolean textIsSelectable = isTextSelectable();

if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && textIsSelectable) {

// The LinkMovementMethod which should handle taps on links has not been installed

// on non editable text that support text selection.

// We reproduce its behavior here to open links for these.

ClickableSpan[] links = mSpannable.getSpans(getSelectionStart(),

getSelectionEnd(), ClickableSpan.class);

if (links.length > 0) {

links[0].onClick(this);

handled = true;

}

}

if (touchIsFinished && (isTextEditable() || textIsSelectable)) {

// Show the IME, except when selecting in read-only text.

final InputMethodManager imm = InputMethodManager.peekInstance();

viewClicked(imm);

if (isTextEditable() && mEditor.mShowSoftInputOnFocus && imm != null) {

imm.showSoftInput(this, 0);

}

// The above condition ensures that the mEditor is not null

mEditor.onTouchUpEvent(event);

handled = true;

}

if (handled) {

return true;

}

}

return superResult;

}

首先如果 mEditor != null 会将touch事件交给mEditor处理,这个 mEditor 其实是和 EditText 有关系的,没有使用 EditText 这里应该是不会被创建的。

去除 mEditor != null 的相关逻辑之后,剩下的相关代码主要如下:

final boolean touchIsFinished = (action == MotionEvent.ACTION_UP)

&& (mEditor == null || !mEditor.mIgnoreActionUpEvent) && isFocused();

if ((mMovement != null || onCheckIsTextEditor()) && isEnabled()

&& mText instanceof Spannable && mLayout != null) {

boolean handled = false;

if (mMovement != null) {

handled |= mMovement.onTouchEvent(this, mSpannable, event);

}

final boolean textIsSelectable = isTextSelectable();

if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && textIsSelectable) {

// The LinkMovementMethod which should handle taps on links has not been installed

// on non editable text that support text selection.

// We reproduce its behavior here to open links for these.

ClickableSpan[] links = mSpannable.getSpans(getSelectionStart(),

getSelectionEnd(), ClickableSpan.class);

if (links.length > 0) {

links[0].onClick(this);

handled = true;

}

}

if (touchIsFinished && (isTextEditable() || textIsSelectable)) {

// Show the IME, except when selecting in read-only text.

final InputMethodManager imm = InputMethodManager.peekInstance();

viewClicked(imm);

if (isTextEditable() && mEditor.mShowSoftInputOnFocus && imm != null) {

imm.showSoftInput(this, 0);

}

// The above condition ensures that the mEditor is not null

mEditor.onTouchUpEvent(event);

handled = true;

}

if (handled) {

return true;

}

}

首先我们先来看一下, mMovement 是否可能为 null,若不为 null,则会调用 handled |= mMovement.onTouchEvent(this, mSpannable, event) 方法。

找啊找,发现在 setText 里面有调用这一段代码,setMovementMethod(LinkMovementMethod.getInstance()); 即 mLinksClickable && !textCanBeSelected() 为 true 的时候给 TextView 设置 MovementMethod。

查看 TextView 的源码我们容易得知 mLinksClickable 的值默认为 true, 而 textCanBeSelected 方法会返回 false,即 mLinksClickable && !textCanBeSelected() 为 true,这个时候会给 TextView 设置 setMovementMethod。 因此在 TextView 的 onTouchEvent 方法中,若 autoLink 等于 true,并且 text 含有 email,phone, webAddress 等的时候,会调用 mMovement.onTouchEvent(this, mSpannable, event) 方法。

if (Linkify.addLinks(s2, mAutoLinkMask)) {

text = s2;

type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;

/*

  • We must go ahead and set the text before changing the

  • movement method, because setMovementMethod() may call

  • setText() again to try to upgrade the buffer type.

*/

setTextInternal(text);

// Do not change the movement method for text that support text selection as it

// would prevent an arbitrary cursor displacement.

if (mLinksClickable && !textCanBeSelected()) {

setMovementMethod(LinkMovementMethod.getInstance());

}

}

boolean textCanBeSelected() {

// prepareCursorController() relies on this method.

// If you change this condition, make sure prepareCursorController is called anywhere

// the value of this condition might be changed.

// 默认 mMovement 为 null

if (mMovement == null || !mMovement.canSelectArbitrarily()) return false;

return isTextEditable()

|| (isTextSelectable() && mText instanceof Spannable && isEnabled());

}

ok ,我们一起在来看一下 mMovement 的 onTouchEvent 方法

MovementMethod 是一个借口,实现子类有 ArrowKeyMovementMethod, LinkMovementMethod, ScrollingMovementMethod 。

这里我们先来看一下 LinkMovementMethod 的 onTouchEvent 方法

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();

最后

代码真的是重质不重量,质量高的代码,是当前代码界提倡的,当然写出高质量的代码肯定需要一个相当高的专业素养,这需要在日常的代码书写中逐渐去吸收掌握,谁不是每天都在学习呀,目的还不是为了一个,为实现某个功能写出高质量的代码。

所以,长征路还长,大家还是好好地做个务实的程序员吧。

最后,小编这里有一系列Android提升学习资料,有兴趣的小伙伴们可以来看下哦~
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 28
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值