java 中將文本中url 轉成 可點擊的鏈接



package com.kuaibao.skuaidi.texthelp;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextToLink {
    /**
     * URL轉換爲鏈接
     * @author 顧鼕鼕
     * @param urlText
     * @return String
     */
    public static String urlToLink(String urlText){
        // url的正則表達式
        String regexp  = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";                                     // 結束條件
        Pattern pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(urlText);
        
        String resultText = "";// (臨時變量,保存轉換後的文本)
        int lastEnd = 0;// 保存每個鏈接最後一會的下標
        
        while(matcher.find()){
        	resultText += urlText.substring(lastEnd, matcher.start()-1);
        	resultText += "<a href=\"" + matcher.group() + "\">" + matcher.group() + "</a>";
        	lastEnd = matcher.end();
        }
        resultText += urlText.substring(lastEnd);
        return resultText;
    }
}

在這裏需要說明的方法:

matcher.find()

最後,將上面返回的結果設置到文本框中,不過要注意的是下面兩行代碼(必須設置了纔可以點擊和轉換哦):

tv_notice_content.setText(Html.fromHtml(TextToLink.urlToLink(帶鏈接的文本)));//
tv_notice_content.setMovementMethod(LinkMovementMethod.getInstance());// 對這個控件設置了以後就可以點擊 了


tv_notice_content.setText(Html.fromHtml("<a href=\"" + <a target=_blank href="http://www.baidu.com">http://www.baidu.com</a> + "\">" + "《點擊查看》" + "</a"));

上面這行代碼呢就是將“《點擊查看》”用來代替前面那段鏈接了。


如果有什麼疑問一定要給我留言哦~我不怕批評,哈哈~望不吝賜教




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章