androidtextviewautolink

Autolink inside a TextView in android


How to give autolink for some part of textview ? For example : My text inside TextView is "Please click here to open this webpage". I want to show link for only the text "here". And I should open that webpage onclick of the text "here" but not on the anywhere of TextView.


Solution

  • Put a String in string.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="txtCredits">Support: <a href="http://www.stackoverflow.com">click here</a></string>
    </resources>
    

    And you can use it in textView like this:

    <TextView
            android:layout_width="fill_parent"
            android:id="@+id/text"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:linksClickable="true"
            android:text="@string/txtCredits" />
    

    EDIT

    For some reason above code does not work properly. So, add below code also,

    TextView t2 = (TextView) findViewById(R.id.text);
    t2.setMovementMethod(LinkMovementMethod.getInstance());
    

    Important: Don't forget to remove autoLink="web" if you are calling setMovementMethod().