Links in TextView

2019-01-06 12:00发布

I need to put a link in a TextView, I have a string that contains the tag <a href="link">Text for link</a> and some other text. The problem is that if I run the project I can see the text but it's not clickable. I tried with the <b> tag too to see if that works and it seems that it doesn't work too.

How can I make this to work without the Linkify usage?

9条回答
Rolldiameter
2楼-- · 2019-01-06 12:42

I can't reply to your answer for some reason; I just wanted to say that you can omit the textView.setText and just put it in a string resource, and set that using android:text. You just need to keep the textView.setMovementMethod(LinkMovementMethod.getInstance());; unfortunately android:linksClickable="true" by itself does not work.

查看更多
We Are One
3楼-- · 2019-01-06 12:44

Getting links working from html is kind of tricky:

  1. Apply your text via xml android:text="@string/… or via setText() (see other answers)

  2. Use textView.setMovementMethod(LinkMovementMethod.getInstance()) to make links clickable (see other answers)

  3. Do NOT add android:autoLink="web" to you XML resource (section TextView), otherwise A-tags are not rendered correctly and are not clickable any longer.

Remark 1:
The OnClickListener can be helpful, if your TextView contains only one link and you want to trigger the navigation even if the user clicks aside your link, but inside the TextView.

Remark 2:
android:linksClickable="true" still does not work (as of Android 3.2), use p. 2 instead

查看更多
Viruses.
4楼-- · 2019-01-06 12:45

Thank you for your help all.

I have managed to make this work, after I have found some examples in the android samples.

here is the code:

textView.setText(Html.fromHtml(
            "<b>text3:</b>  Text with a " +
            "<a href=\"http://www.google.com\">link</a> " +
            "created in the Java source code using HTML."));
textView.setMovementMethod(LinkMovementMethod.getInstance());

Hope this help others...

查看更多
对你真心纯属浪费
5楼-- · 2019-01-06 12:50

The Solution : Linkify.addLinks(chatText,Linkify.ALL);

查看更多
做自己的国王
6楼-- · 2019-01-06 12:50

To add the links dynamically (fetched from the server), this works:

textView.setText(Html.fromHtml(
                "<a href=" + response.getLink()
                        + ">" + context.getString(R.string.link_from_server) + "</a> "));

and in XML add this:

android:linksClickable="true"

If your strings.xml has this:

<string name="link_from_server">Dynamic Link</string>

This will add "Dynamic Link" to your text view and if you touch on this, it will go the link provided by your server.

查看更多
我只想做你的唯一
7楼-- · 2019-01-06 12:54

This works pretty correcty:(In textview properties,inside xml file)

android:autolink="web"
查看更多
登录 后发表回答