Search code examples
androidxmlandroid-layouttextview

android - TextView autoLink


I want to show links in TextView and whenever user cliks the link, it must open. xml Code:

<TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:linksClickable="true"
            android:autoLink="web" />

Java Code:

textView.setMovementMethod(LinkMovementMethod.getInstance());

Yes it's working and makes links blue and underline. But when I use a word for example ".hello" it becomes a link because of dot. So If a dot and a word is adjoining, it becomes a link. How can I solve this problem? Thanks.


Solution

  • First remove linksClickable & autoLink attribute from xml

    then you have to check that in given string is there any url available using regex. Using Following Code :

    private boolean containsURL(String content) {
        String REGEX = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        Pattern p = Pattern.compile(REGEX, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(content);
        if (m.find()) {
            return true;
        }
        return false;
    }
    

    if in given string contains url then it will be shown text in blue color.

    TextView textView = findViewById(R.id.textView);
    textView.setText("Any String value");
    
    if (containsURL("Any String value")) {
        Linkify.addLinks(textView, Linkify.WEB_URLS);
        textView.setLinksClickable(true);
    }