我正在尝试在其视图中创建一个带有链接的 ListView。就像推特应用程序一样。现在这就是我正在做的事情:我在 TextView 中设置了 android:autoLink="all"。
private static class TweetViewHolder {
public LinkifiedTextView text;
public TextView time;
public ImageView authorImage;
}
holder.text.setText(post.getTweet().getText());
Pattern pattern = Pattern.compile("@+[a-zA-Z_]+");
Linkify.addLinks(holder.text, pattern, "http://www.twitter.com/", null, myTransformFilter);
pattern = Pattern.compile("#+[a-zA-Z_]+");
Linkify.addLinks(holder.text, pattern, "http://www.twitter.com/", null, myTransformFilter);
TransformFilter myTransformFilter = new TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
return url.substring(1); //remove the $ sign
}
};
这是我的“LinkifiedTextView”代码:
@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) {
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;
}
}
}
return false;
}
现在代码在“Spannable buffer = (Spannable) text;”上崩溃。为什么会这样,我怎样才能改变事情以使其发挥作用?谢谢!