TextView怎么才能使URLSpan部分和非URLSpan部分分别响应
答案:1 悬赏:70 手机版
解决时间 2021-02-18 17:18
- 提问者网友:星軌
- 2021-02-17 23:37
TextView怎么才能使URLSpan部分和非URLSpan部分分别响应
最佳答案
- 五星知识达人网友:枭雄戏美人
- 2021-02-17 23:43
你可以参考 LinkMovementMethod 写一个 自定义的 LinkMovementMethod。
主要的处理是在 onTouchEvent 时,当找不到ClickableSpan事件,则调用 你传进来的 listener 事件。
然后 textview 调用setMovementMethod(),传入自定义的LinkMovementMethod就好了。
[mw_shl_code=java,true] @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) {
link[0].onClick(widget);
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer, buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
}
return true;
} else {
Selection.removeSelection(buffer);
if (action == MotionEvent.ACTION_UP && listener != null) {
listener.onTextClicked();
}
}
}
return super.onTouchEvent(widget, buffer, event);
}
[/mw_shl_code]
主要的处理是在 onTouchEvent 时,当找不到ClickableSpan事件,则调用 你传进来的 listener 事件。
然后 textview 调用setMovementMethod(),传入自定义的LinkMovementMethod就好了。
[mw_shl_code=java,true] @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) {
link[0].onClick(widget);
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer, buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]));
}
return true;
} else {
Selection.removeSelection(buffer);
if (action == MotionEvent.ACTION_UP && listener != null) {
listener.onTextClicked();
}
}
}
return super.onTouchEvent(widget, buffer, event);
}
[/mw_shl_code]
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯