我正在使用TextView,我autolink="web"在XML文件中设置了属性.我也onClickListener为这个TextView 实现了.问题是,当TextView中的文本包含超链接时,如果我触摸该链接,链接将在浏览器中打开,但同时onClickListener也会触发.我不希望这样.
我想要的是,如果我触摸超链接,clickListener不应该触发.如果我触摸没有超链接的文本部分,它应该只会触发.有什么建议吗?
bin*_*ary 22
你可以使用Textview类的getSelectionStart()和getSelectionEnd()函数来解决这个问题,
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ClassroomLog.log(TAG, "Textview Click listener ");
if (tv.getSelectionStart() == -1 && tv.getSelectionEnd() == -1) {
//This condition will satisfy only when it is not an autolinked text
//Fired only when you touch the part of the text that is not hyperlinked
}
}
});
Run Code Online (Sandbox Code Playgroud)
这可能是一个迟到的回复,但可能对那些正在寻找解决方案的人有用.
其中一篇@CommonsWare帖子有助于拦截自动链接OnClick事件.
private void fixTextView(TextView tv) {
SpannableString current = (SpannableString) tv.getText();
URLSpan[] spans =
current.getSpans(0, current.length(), URLSpan.class);
for (URLSpan span : spans) {
int start = current.getSpanStart(span);
int end = current.getSpanEnd(span);
current.removeSpan(span);
current.setSpan(new DefensiveURLSpan(span.getURL()), start, end,
0);
}
}
public static class DefensiveURLSpan extends URLSpan {
private String mUrl;
public DefensiveURLSpan(String url) {
super(url);
mUrl = url;
}
@Override
public void onClick(View widget) {
// openInWebView(widget.getContext(), mUrl); // intercept click event and do something.
// super.onClick(widget); // or it will do as it is.
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码应用如下.它将遍历所有可链接的文本,并将单击事件替换为上面的事件处理程序.
fixTextView(textViewContent);
Run Code Online (Sandbox Code Playgroud)
您可以尝试这个,而不是使用 onClickListener。
private void addLink() {
tvLink = (TextView) findViewById(R.id.tvInfo2);
String strURL = UrlLoader.getCodeUrl();
// Make the url string clicable and take action in its onclick
SpannableString spanUrl = SpannableString.valueOf(strURL);
spanUrl.setSpan(new InternalURLSpan(new OnClickListener() {
public void onClick(View v) {
//Do Some action
}
}), 0, spanUrl.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tvLink.setText(spanUrl);
// We probably also want the user to jump to your link by moving the
// focus (e.g. using the trackball), which we can do by setting the
// proper movement method:
MovementMethod m = tvLink.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
if (tvLink.getLinksClickable()) {
tvLink.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
Run Code Online (Sandbox Code Playgroud)
另外,在布局 XML 文件中,不要忘记添加
<TextView android:layout_width="wrap_content" android:linksClickable="true"
android:layout_height="wrap_content" android:id="@+id/tvInfo2" android:text="@string/url_link" />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11544 次 |
| 最近记录: |