Autolink inside a TextView in android

前端 未结 5 1967
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 02:57

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 \

相关标签:
5条回答
  • 2020-12-14 03:15

    Use HTML syntax in strings.xml:

    <string name="test">Click &lt;a href="http://vtuhtan.info"&gt;here&lt;/a&gt;</string>
    

    Set TextView properties to have links clickable and auto link.

    TextView tv = findViewById(R.id.textView);
    tv.setText(Html.fromHtml(getResources().getString(R.string.test)));
    
    0 讨论(0)
  • 2020-12-14 03:21

    You can test it with following code:

     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="http://www.yahoo.com"
        android:autoLink="web"
        />
    
    0 讨论(0)
  • 2020-12-14 03:23

    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:autoLink="web"
            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());
    
    0 讨论(0)
  • 2020-12-14 03:23

    use simple Url in strings.xml :

    <string name="autolink_val">Please Click Here : http://www.google.com</string>
    

    And in Java code write this:

    <TextView android:id="@+id/linkVal"   
              android:layout_width="wrap_content" 
              android:layout_height="wrap_content" 
              android:autoLink="web" 
              android:text="@string/autolink_val1"/>`
    
    0 讨论(0)
  • 2020-12-14 03:26

    Textviews are capable of displaying HTML, which solves your problem. Wrap what you want clickable in a hyperlink:

    String html = "My link is <a href=\"http://google.com\">here</a>";
    myTextView.setText(Html.fromHtml(html));
    
    0 讨论(0)
提交回复
热议问题