I'm trying to retrieve the URL of the clicked link in an EditText . I want to touch a link, and then do something with its URL. The closest I've gotten is to determine if the span where the cursor sits is a URLSpan style:
int s1 = Math.max(mText.getSelectionStart(), 0);
int s2 = Math.max(mText.getSelectionEnd(), 0);
Spannable raw = new SpannableString(mText.getText());
CharacterStyle[] spans = raw.getSpans(s1, s2, CharacterStyle.class);
for (CharacterStyle span : spans) {
if(span.getClass().equals(android.text.style.URLSpan.class)){
//is a link, but what is the URL?
}
}
If I convert it all to an HTML string then I don't know how to relate the cursor position of plain text to the html text. I can get all the URLs in an EditText with getUrls()
, but still do not know which one was clicked. If I could do something like: EditText.getPortion(start, end).getUrls()
, that would be closer, but I've seen no methods for anything like that so far.
Try this code,
EditText editText = (EditText) findViewById(R.id.edittext);
editText.setText(someContent);
Linkify.addLinks(editText, Linkify.ALL);
Log.d(TAG, "HTML: " + Html.toHtml(editText.getEditableText()));
and see this tutorial also,
http://developer.android.com/reference/android/text/util/Linkify.html
I realize this is a 4 year old response, but to answer for future visitors:
for (CharacterStyle span : spans) {
if(span.getClass().equals(android.text.style.URLSpan.class)){
//you almost had it here, just cast the span as a URLspan
URLSpan u = (URLSpan)spans[j];
String span_url = u.getURL();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.