我在文本视图中显示一些文本,这是列表视图中的一个元素。我正在使用Linkify.addLinks在textview中添加链接。但问题是包含链接的完整行变得可点击而不仅仅是我打算链接的文本(单词)。
我的功能:
private static void linkifyPattern(TextView view, String text, String url) {
Linkify.TransformFilter filter = new Linkify.TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
return url;
}
};
Pattern pattern = Pattern.compile(text);
Linkify.addLinks(view, pattern, null, null, filter);
}
我正在使用的自定义文本视图包含:
@Override
public boolean onTouchEvent(MotionEvent event) {
TextView widget = (TextView) this;
Object text = widget.getText();
if (text instanceof Spanned) {
Spannable buffer = (Spannable) text;
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) {
for (int i = 0; i < link.length;) {
System.out.println("Link:: " + link[i].toString());
if (action == MotionEvent.ACTION_UP) {
link[i].onClick(widget);
} else if (action == MotionEvent.ACTION_DOWN) {
Selection.setSelection(buffer,
buffer.getSpanStart(link[i]),
buffer.getSpanEnd(link[i]));
}
return true;
}
}
}
}
return false;
}
文本视图的xml代码是:
<com.presenter.custom.CustomTextView
android:id="@+id/news_message_collapsed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:focusable="false"
android:focusableInTouchMode="false"
android:paddingRight="@dimen/news_view_text_right_padding"
android:textColor="@color/black"
android:textColorLink="@color/red"
android:textSize="@dimen/news_view_text_size" />
谢谢