如何在TextView中创建以http或www开头的可点击链接

时间:2016-02-25 14:41:14

标签: java android regex textview

我已使用android:autoLinkTextView中点击链接,但问题是我需要检查链接是否以httpwww开头,因为例如,如果文本是“某个句子。发生错误”,则将文本设置为可点击,我想避免这种情况。有什么想法吗?

----------------这是解决方案:----------------

private void setUrlClickable(TextView textViewContent, Spanned text) {
        SpannableString spannableString = new SpannableString(text);
        final Matcher matcher = Pattern.compile("(http|www)\\S*").matcher(spannableString);
        while (matcher.find()) {
            spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.list_section)), matcher.start(), matcher.end(), 0);
            spannableString.setSpan(new TextClickable(matcher.group(0)), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        textViewContent.setText(spannableString);
        textViewContent.setMovementMethod(LinkMovementMethod.getInstance());
    }

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式来验证所需的文本。例如,您可以使用以下正则表达式来检查字符串是否为http,ftp,... link

String regex = "^(https?|ftp)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";

然后创建一个checkText方法来启用authoLink:

private static boolean checkText(String s, String regex) {
    try {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(s);
        return matcher.matches();
    } catch (RuntimeException e) {
    return false;
}  

答案 1 :(得分:1)

假设您的文字看起来像这样“这个链接www.yoursite.com是可点击的”,并且您只想点击“www.yoursite.com”部分,您可以这样做:

private void setText(String text){
    String regexPattern = "(http|www)\\S*";
    final Matcher matcher = Pattern.compile(regexPattern).matcher(text);
    SpannableStringBuilder strBuilder = new SpannableStringBuilder(text);
    while(matcher.find()){

        ClickableSpan clickable = new ClickableSpan() {
            public void onClick(View view) {
                // Do something with span.getURL() to handle the link click...
            }
        };

        strBuilder.setSpan(clickable, matcher.start(), matcher.end(), 0);

    }
}

希望能为你效劳。