2013-08-28 38 views
1

我試圖獲取點擊鏈接的URLEditText。我想觸摸一個鏈接,然後使用其URL進行操作。我已經得到的最接近的是,以確定是否在光標坐在跨度是URLSpan風格:獲取Android EditText中點擊鏈接的URL或HTML

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? 

    } 
} 

如果我把它全部轉換成HTML字符串,然後我不知道如何與的光標位置純文本到html文本。我可以通過getUrls()獲得EditText中的所有網址,但仍不知道點擊了哪個網址。如果我能做到這樣的事情:EditText.getPortion(start, end).getUrls(),那會更接近,但我目前還沒有看到類似的方法。

回答

2

試試這個代碼,

EditText editText = (EditText) findViewById(R.id.edittext); 
editText.setText(someContent); 
Linkify.addLinks(editText, Linkify.ALL); 
Log.d(TAG, "HTML: " + Html.toHtml(editText.getEditableText())); 

,並請參閱本教程還

http://developer.android.com/reference/android/text/util/Linkify.html

+0

謝謝,但我並沒有試圖將網址變成鏈接。我試圖在點擊鏈接文本時獲取鏈接文字的網址。 – Ael

0

我意識到這是一個4歲的迴應,但回答爲將來遊客:

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(); 
    } 
}