[英]TextView with custom links
是否有一種簡單的方法可以為Android TextView組件創建自定義鏈接並處理其“觸摸”行為?
我沒有在Internet上找到任何解決方案,但附帶了自己的解決方案。
有一種簡單的方法可以為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);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.