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

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
MotionEvent.ACTION_DOWN) {

int x = (int) event.getX();

int y = (int) event.getY();

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-y2z5z7aJ-1715767716492)]

[外链图片转存中…(img-cBYPUEE0-1715767716494)]

[外链图片转存中…(img-AoYzTN1U-1715767716495)]

[外链图片转存中…(img-evKXAowI-1715767716496)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值