Dynamically setting links to text in strings.xml

后端 未结 4 1931
野趣味
野趣味 2020-12-15 11:12

I\'m trying to make an app with localisation built in, but I want a way that I can create a web link within the text, the URL being defined elsewhere (for ease of maintenanc

相关标签:
4条回答
  • 2020-12-15 11:14

    You have to implement

    setMovementMethod(LinkMovementMethod.getInstance());
    

    on your Textview

    Here is a better example:

    clickable-urls-in-android-textviews

    0 讨论(0)
  • 2020-12-15 11:18

    The problem is your "a href" link tags are within strings.xml and being parsed as tags when strings.xml is parsed, which you don't want. Meaning you need to have it ignore the tags using XML's CDATA:

    <string name="sampleText">Sample text <![CDATA[<a href="http://www.google.com">link1</a>]]></string>

    And then you can continue with Html.fromHtml() and make it clickable with LinkMovementMethod:

    TextView tv = (TextView) findViewById(R.id.textHolder);
    tv.setText(Html.fromHtml(getString(R.string.sampleText)));
    tv.setMovementMethod(LinkMovementMethod.getInstance());
    
    0 讨论(0)
  • 2020-12-15 11:26

    Try using Html.fromHtml() to convert the HTML into a Spannable that you put into the TextView. With what you have in #1, I would expect the TextView to show the HTML source, not rendered HTML.

    0 讨论(0)
  • In your layout set android:autoLink to web

    <TextView android:text="@string/text_with_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autoLink="web" />
    

    And in strings.xml just add the URL(s).

    <string name="text_with_url">http://stackoverflow.com/ FTW!</string>
    
    0 讨论(0)
提交回复
热议问题