是否有一种简单的方法可以创建自定义链接并处理他们的触摸' Android TextView组件的行为?
我在互联网上找不到任何解决方案,但我自己来了。
答案 0 :(得分:1)
有一种简单的方法可以为textview创建自定义链接并处理触摸事件导致的行为。 为了避免编写和编写自己的模式包装器,使用了Html包装器。
TextView tView = ((TextView)v.findViewById(R.id.otp_activation_notification));
Spanned ssBuilder = Html.fromHtml("Not a link <a href=\"foo://haha/arg1/arg2?q1=1&q2=2\">The first link</a> bla bla "
+ " <a href=\"foo://haha2?q3=3\">The second link</a>");
tView.setText(ssBuilder);
tView.setMovementMethod(new LinkMovementMethod(){
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
//TODO: In order to override the links actions
int x = (int) event.getX();
int y = (int) event.getY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
try {
URLSpan[] urlSpans = buffer.getSpans(off, off, URLSpan.class);
if (urlSpans != null && urlSpans.length > 0) {
Uri uri = Uri.parse(urlSpans[0].getURL());
String scheme = uri.getScheme();
if ("foo".equals(scheme)) {
String command = uri.getAuthority();
if ("haha".equals(command)) {
List<String> arguments = uri.getPathSegments();
String q1 = uri.getQueryParameter("q1");
String q2 = uri.getQueryParameter("q2");
//TODO: Execute command (pay attention for MotionEvent)
return true;
} else if ("haha2".equals(command)) {
String q3 = uri.getQueryParameter("q2");
//TODO: Execute command2 (pay attention for MotionEvent)
return true;
}
return false;
}
}
} catch (Exception e) {
//Log: unable to parse link;
}
//return false in case you don't want to use default behavior.
return super.onTouchEvent(widget, buffer, event);
}
});