1
2
3
4
5
|
TextView tv = (TextView)findViewById(R.id.tv);
SpannableString sp =
new
SpannableString(
"此处为tv里显示的内容"
);
sp.setSpan(
new
URLSpan(
"http://www.baidu.com"
),
3
,
8
, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(sp);
tv.setMovementMethod(LinkMovementMethod.getInstance());
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
@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);
//获取textview里的超链接对象,并用ClickableSpan数组盛装
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
;
//处理结束后返回true,这里一定要注意:当返回值为true时则表示点击事件已经被,就再也不会继续传递了
}
else
{
Selection.removeSelection(buffer);
}
}
return
super
.onTouchEvent(widget, buffer, event);
}
|