如何使 TextView 中的链接可点击

发布于 2024-08-30 07:35:17 字数 836 浏览 8 评论 0原文

我定义了以下 TextView:

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="@string/txtCredits"
    android:autoLink="web" android:id="@+id/infoTxtCredits"
    android:layout_centerInParent="true"
    android:linksClickable="true"/>

其中 @string/txtCredits 是包含 链接文本 的字符串资源。

Android 突出显示 TextView 中的链接,但它们不响应点击。我做错了什么?我是否必须为 Activity 中的 TextView 设置 onClickListener 才能实现如此简单的操作?

看起来这与我定义字符串资源的方式有关。

这不起作用:

<string name="txtCredits"><a href="http://www.google.com">Google</a></string>

但这确实有效: 这

<string name="txtCredits">www.google.com</string>

是一个无赖,因为我更愿意显示文本链接而不是显示完整的 URL。

I have the following TextView defined:

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="@string/txtCredits"
    android:autoLink="web" android:id="@+id/infoTxtCredits"
    android:layout_centerInParent="true"
    android:linksClickable="true"/>

where @string/txtCredits is a string resource that contains <a href="some site">Link text</a>.

Android is highlighting the links in the TextView, but they do not respond to clicks. What am I doing wrong? Do I have to set an onClickListener for the TextView in my activity for something as simple as this?

It looks like it has to do with the way I define my string resource.

This does not work:

<string name="txtCredits"><a href="http://www.google.com">Google</a></string>

But this does:

<string name="txtCredits">www.google.com</string>

Which is a bummer because I would much rather show a text link than show the full URL.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

骄傲 2024-09-06 07:35:17

在 API 演示中,我找到了问题的解决方案:

文件 Link.java

    // text2 has links specified by putting <a> tags in the string
    // resource.  By default these links will appear but not
    // respond to user input.  To make them active, you need to
    // call setMovementMethod() on the TextView object.

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

我删除了 TextView 上的大部分属性以匹配演示中的内容。

<TextView
    android:id="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/txtCredits"/>

这解决了它。发现和修复是相当困难的。

重要:如果您调用 setMovementMethod(),请不要忘记删除 autoLink="web"

Buried in the API demos, I found the solution to my problem:

File Link.java:

    // text2 has links specified by putting <a> tags in the string
    // resource.  By default these links will appear but not
    // respond to user input.  To make them active, you need to
    // call setMovementMethod() on the TextView object.

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

I removed most of the attributes on my TextView to match what was in the demo.

<TextView
    android:id="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/txtCredits"/>

That solved it. It is pretty difficult to uncover and fix.

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

但可醉心 2024-09-06 07:35:17

我只使用 android:autoLink="web" 并且工作正常。单击链接将打开浏览器并显示正确的页面。

我可以猜测的一件事是链接上方还有其他一些视图。透明的东西会填充整个父级,但不会在链接上方显示任何内容。在这种情况下,单击将转到此视图而不是链接。

I'm using only android:autoLink="web" and it works fine. A click on the link opens the browser and shows the correct page.

One thing I could guess is that some other view is above the link. Something that is transparent fills the whole parent but don't displays anything above the link. In this case the click goes to this view instead of the link.

雪化雨蝶 2024-09-06 07:35:17

花了一些时间后,我发现:

  • 如果 HTML 中有完整链接,android:autoLink="web" 就可以工作。以下内容将以蓝色突出显示并且可单击:
  • view.setMovementMethod(LinkMovementMethod.getInstance()); 将使用以下内容(将突出显示并可点击):


请注意,第三个选项有一个超链接,但链接的描述(标签之间的部分)本身并不是链接。 android:autoLink="web" 不能使用此类链接。

  • android:autoLink="web" 如果在 XML 中设置,将覆盖 view.setMovementMethod(LinkMovementMethod.getInstance()); (即;第三种链接将突出显示,但不可点击)。

这个故事的寓意是在代码中使用 view.setMovementMethod(LinkMovementMethod.getInstance()); 并确保您没有 android:autoLink="web"如果您希望所有链接都可点击,请在您的 XML 布局中添加。

After spending some time with this, I have found that:

  • android:autoLink="web" works if you have full links in your HTML. The following will be highlighted in blue and clickable:
  • Some text <a href="http://www.google.com">http://www.google.com</a>
  • Some text http://www.google.com
  • view.setMovementMethod(LinkMovementMethod.getInstance()); will work with the following (will be highlighted and clickable):
  • Some text <a href="http://www.google.com">http://www.google.com</a>
  • Some text http://www.google.com
  • Some text <a href="http://www.google.com">Go to Google</a>

Note that the third option has a hyperlink, but the description of the link (the part between the tags) itself is not a link. android:autoLink="web" does NOT work with such links.

  • android:autoLink="web" if set in XML will override view.setMovementMethod(LinkMovementMethod.getInstance()); (i.e.; links of the third kind will be highlighted, but not clickable).

The moral of the story is use view.setMovementMethod(LinkMovementMethod.getInstance()); in your code and make sure you don't have android:autoLink="web" in your XML layout if you want all links to be clickable.

黑寡妇 2024-09-06 07:35:17

上面的解决方案对我不起作用,但以下解决方案对我有用(而且看起来更干净)。
首先,在字符串资源中,使用 HTML 实体编码定义标签开头 V 形,即:

<a href="http://www.google.com">Google</a>

并且

<a href="http://www.google.com">Google</a>

一般来说,对字符串中的所有 V 形进行编码。顺便说一句,链接必须以 http:// 开头

然后(按照此处的建议)设置此TextView 上的选项:

 android:linksClickable="true"

最后,在代码中执行:

((TextView) findViewById(R.id.your_text_view)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.your_text_view)).setText(Html.fromHtml(getResources().getString(R.string.string_with_links)));

就是这样。不需要正则表达式或其他手动操作。

The above solutions didn't work for me, but the following did (and it seems a bit cleaner).
First, in the string resource, define your tag opening chevrons using the HTML entity encoding, i.e.:

<a href="http://www.google.com">Google</a>

And not:

<a href="http://www.google.com">Google</a>

In general, encode all the chevrons in the string like that. BTW, the link must start with http://

Then (as suggested here) set this option on your TextView:

 android:linksClickable="true"

Finally, in code, do:

((TextView) findViewById(R.id.your_text_view)).setMovementMethod(LinkMovementMethod.getInstance());
((TextView) findViewById(R.id.your_text_view)).setText(Html.fromHtml(getResources().getString(R.string.string_with_links)));

That's it. No regular expressiones or other manual hacks are required.

很糊涂小朋友 2024-09-06 07:35:17

我只是使用了这个:

Linkify.addLinks(TextView, Linkify.ALL);

它使链接可点击,此处。

I simply used this:

Linkify.addLinks(TextView, Linkify.ALL);

It makes the links clickable, given here.

差↓一点笑了 2024-09-06 07:35:17

如果你想添加一个类似 HTML 的链接,你需要做的就是:

  • 添加一个类似 HTML 的资源字符串:

     Google
    
  • 将视图添加到布局,根本没有特定于链接的配置:

    <前><代码>`

  • 以编程方式将适当的 MovementMethod 添加到您的 TextView:

     mLink = (TextView) findViewById(R.id.link);
      if (mLink != null) {
        mLink.setMovementMethod(LinkMovementMethod.getInstance());
      }
    

就是这样!是的,像“autoLink”和“linksClickable”这样的选项仅适用于显式链接(不包含在 HTML 标签中)对我来说也是非常误导的......

If you want to add an HTML-like link, all you need to do is:

  • add a resource HTML-like string:

      <string name="link"><a href="https://www.google.pl/">Google</a></string>
    
  • add your view to the layout with no link-specific configuration at all:

      <TextView
         android:id="@+id/link"
         android:text="@string/link" />`
    
  • add the appropriate MovementMethod programmatically to your TextView:

      mLink = (TextView) findViewById(R.id.link);
      if (mLink != null) {
        mLink.setMovementMethod(LinkMovementMethod.getInstance());
      }
    

That's it! And yes, having options like "autoLink" and "linksClickable" working on explicit links only (not wrapped into HTML tags) is very misleading to me too...

小嗷兮 2024-09-06 07:35:17

以下内容应该适用于任何在 Android 应用程序中寻找文本和超链接组合的人。

string.xml 中:

<string name="applink">Looking for Digital Visiting card? 
<a href="https://play.google.com/store/apps/details?id=com.themarkwebs.govcard">Get it here</a>
</string>

现在您可以在任何给定的 View 中使用此 string,如下所示:

<TextView
    android:id="@+id/getapp"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:gravity="center"
    android:textColor="@color/main_color_grey_600"
    android:textSize="15sp"
    android:text="@string/applink"/>

现在,在您的 Activity 或 Fragment 中,执行以下操作:

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

到目前为止,您不需要使用此方法设置 android:autoLink="web"android:linksClickable="true"

The following should work for anyone who is looking for a combination of text and hyperlink within an Android app.

In string.xml:

<string name="applink">Looking for Digital Visiting card? 
<a href="https://play.google.com/store/apps/details?id=com.themarkwebs.govcard">Get it here</a>
</string>

Now you can utilise this string in any given View like this:

<TextView
    android:id="@+id/getapp"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:gravity="center"
    android:textColor="@color/main_color_grey_600"
    android:textSize="15sp"
    android:text="@string/applink"/>

Now, in your Activity or Fragment, do the following:

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

By now, you don't require to set android:autoLink="web" or android:linksClickable="true" using this approach.

唠甜嗑 2024-09-06 07:35:17

我将此行添加到 TextView 中: android:autoLink="web"

下面是布局文件中的使用示例。

布局.xml

<TextView
    android:id="@+id/txtLostpassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:autoLink="email"
    android:gravity="center"
    android:padding="20px"
    android:text="@string/lostpassword"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
    android:id="@+id/txtDefaultpassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:autoLink="web"
    android:gravity="center"
    android:padding="20px"
    android:text="@string/defaultpassword"
    android:textAppearance="?android:attr/textAppearanceSmall" />

字符串.xml

<string name="lostpassword">If you lost your password please contact <a href="mailto:[email protected]?Subject=Lost%20Password" target="_top">[email protected]</a></string>

<string name="defaultpassword">User Guide <a href="http://www.cleverfinger.com.au/user-guide/">http://www.cleverfinger.com.au/user-guide/</a></string>

I added this line to the TextView: android:autoLink="web"

Below is an example of usage in a layout file.

layout.xml

<TextView
    android:id="@+id/txtLostpassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:autoLink="email"
    android:gravity="center"
    android:padding="20px"
    android:text="@string/lostpassword"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
    android:id="@+id/txtDefaultpassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:autoLink="web"
    android:gravity="center"
    android:padding="20px"
    android:text="@string/defaultpassword"
    android:textAppearance="?android:attr/textAppearanceSmall" />

string.xml

<string name="lostpassword">If you lost your password please contact <a href="mailto:[email protected]?Subject=Lost%20Password" target="_top">[email protected]</a></string>

<string name="defaultpassword">User Guide <a href="http://www.cleverfinger.com.au/user-guide/">http://www.cleverfinger.com.au/user-guide/</a></string>
究竟谁懂我的在乎 2024-09-06 07:35:17

希望这对您有帮助;

String value = "<html>Visit my blog <a href=\"http://www.maxartists.com\">mysite</a> View <a href=\"sherif-activity://myactivity?author=sherif&nick=king\">myactivity</a> callback</html>";
TextView text = (TextView) findViewById(R.id.text);

text.setText(Html.fromHtml(value));
text.setMovementMethod(LinkMovementMethod.getInstance());

I hope this will help you;

String value = "<html>Visit my blog <a href=\"http://www.maxartists.com\">mysite</a> View <a href=\"sherif-activity://myactivity?author=sherif&nick=king\">myactivity</a> callback</html>";
TextView text = (TextView) findViewById(R.id.text);

text.setText(Html.fromHtml(value));
text.setMovementMethod(LinkMovementMethod.getInstance());
善良天后 2024-09-06 07:35:17

对我来说最简单的事情是使用 Linkify

TextView txt_Message = (TextView) view.findViewById(R.id.txt_message);
txt_Message.setText("This is link https://www.google.co.in/");
Linkify.addLinks(txt_Message, Linkify.WEB_URLS);

它会自动从文本视图中的文本中检测网址。

The easiest thing that worked for me was to use Linkify

TextView txt_Message = (TextView) view.findViewById(R.id.txt_message);
txt_Message.setText("This is link https://www.google.co.in/");
Linkify.addLinks(txt_Message, Linkify.WEB_URLS);

And it will automatically detect the web URLs from the text in the textview.

雄赳赳气昂昂 2024-09-06 07:35:17

您只需要在 XML 的文本视图中添加以下内容:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:autoLink="web"/>

You only need to add this in the text view in XML:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:autoLink="web"/>
很酷不放纵 2024-09-06 07:35:17

还管理 Linkify 文本颜色

在此处输入图像描述

tv_customer_care_no.setLinkTextColor(getResources().getColor(R.color.blue));
tv_customer_care_no.setText("For us to reach out to you, please fill the details below or contact our customer care at 18004190899 or visit our website http://www.dupont.co.in/corporate-links/contact-dupont.html");
Linkify.addLinks(tv_customer_care_no, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);
Linkify.addLinks(tv_customer_care_no, Linkify.ALL);

Manage Linkify text color also

Enter image description here

tv_customer_care_no.setLinkTextColor(getResources().getColor(R.color.blue));
tv_customer_care_no.setText("For us to reach out to you, please fill the details below or contact our customer care at 18004190899 or visit our website http://www.dupont.co.in/corporate-links/contact-dupont.html");
Linkify.addLinks(tv_customer_care_no, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);
Linkify.addLinks(tv_customer_care_no, Linkify.ALL);
递刀给你 2024-09-06 07:35:17

通过使用linkify

< strong>Linkify 接受一段文本和一个正则表达式,并将文本中的所有正则表达式匹配转换为可点击的链接:

TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("http://example.com");
Linkify.addLinks(textView, Linkify.WEB_URLS);

不要忘记

import android.widget.TextView;

By using linkify:

Linkify takes a piece of text and a regular expression and turns all of the regex matches in the text into clickable links:

TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("http://example.com");
Linkify.addLinks(textView, Linkify.WEB_URLS);

Don't forget to

import android.widget.TextView;
甜扑 2024-09-06 07:35:17

这是一个非常一行的 Android 代码,无论字符串是什么、数据是什么,都可以从 textView 中选择电话和 URL。您不需要为此使用任何 HTML 标记。

TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText("some URL is www.google.com phone 7504567890 another URL lkgndflg.com ");

// Makes the textView's Phone and URL (hyperlink) select and go.
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);

Here is a very one-line Android code to make phone and URL selectable from textView no matter what the string is and what the data is. You don’t need to use any HTML tags for this.

TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText("some URL is www.google.com phone 7504567890 another URL lkgndflg.com ");

// Makes the textView's Phone and URL (hyperlink) select and go.
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS);
揽月 2024-09-06 07:35:17

Richard,下次,您应该在布局 XML 的 TextView 下添加此代码。

android:autoLink="all"

应该是这样的。

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="@string/txtCredits"
    android:id="@+id/infoTxtCredits"
    android:autoLink="all"
    android:linksClickable="true">
</TextView>

您不需要使用此代码 (t2.setMovementMethod(LinkMovementMethod.getInstance());) 来使链接可单击。

另外,事实是:只要设置了 autoLinklinksClickable,就不要忘记将其添加到 String.xml 文件中这样可点击的链接就可以工作。

<string name="txtCredits"><a href="http://www.google.com">Google</a></string>

Richard, next time, you should add this code under TextView at the layout XML instead.

android:autoLink="all"

This should be like this.

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="@string/txtCredits"
    android:id="@+id/infoTxtCredits"
    android:autoLink="all"
    android:linksClickable="true">
</TextView>

You don't need to use this code (t2.setMovementMethod(LinkMovementMethod.getInstance());) in order to make the link clickable.

Also, here's the truth: as long as you set the autoLink and the linksClickable, don't forget to add this at String.xml file so that the clickable link will work.

<string name="txtCredits"><a href="http://www.google.com">Google</a></string>
本宫微胖 2024-09-06 07:35:17

我注意到使用 android:autoLink="web" 因此

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:autoLink="web"/>

对于 URL 来说工作正常,但由于我也想链接一个电子邮件地址和电话号码,所以我最终使用了这一行 < code>android:autoLink="all" 像这样

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:autoLink="all"/>

,它就像一个魅力。

I noticed that using android:autoLink="web" thus

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:autoLink="web"/>

worked OK for URLs but since I had an e-mail address and phone number that I wanted to link as well, I ended up using this line android:autoLink="all" like this

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:autoLink="all"/>

and it worked like a charm.

指尖微凉心微凉 2024-09-06 07:35:17

接受的答案是正确的,但是这意味着电话号码、地图、电子邮件地址和常规链接(例如,不带 href 标签的 http://google.com不再可点击,因为 XML 内容中不能有自动链接。

我发现的唯一让一切可点击的完整解决方案如下:

Spanned text = Html.fromHtml(myString);
URLSpan[] currentSpans = text.getSpans(0, text.length(), URLSpan.class);
SpannableString buffer = new SpannableString(text);
Linkify.addLinks(buffer, Linkify.ALL);
for (URLSpan span : currentSpans) {
    int end = text.getSpanEnd(span);
    int start = text.getSpanStart(span);
    buffer.setSpan(span, start, end, 0);
}
textView.setText(buffer);
textView.setMovementMethod(LinkMovementMethod.getInstance());

并且TextView不应该android:autolink。也不需要 android:linksClickable="true" ;默认情况下是这样。

The accepted answer is correct, but it will mean that phone numbers, maps, email addresses, and regular links, e.g., http://google.com without href tags will no longer be clickable since you can't have an autolink in the XML content.

The only complete solution to have everything clickable that I have found is the following:

Spanned text = Html.fromHtml(myString);
URLSpan[] currentSpans = text.getSpans(0, text.length(), URLSpan.class);
SpannableString buffer = new SpannableString(text);
Linkify.addLinks(buffer, Linkify.ALL);
for (URLSpan span : currentSpans) {
    int end = text.getSpanEnd(span);
    int start = text.getSpanStart(span);
    buffer.setSpan(span, start, end, 0);
}
textView.setText(buffer);
textView.setMovementMethod(LinkMovementMethod.getInstance());

And the TextView should not have android:autolink. There's no need for android:linksClickable="true" either; it's true by default.

我的奇迹 2024-09-06 07:35:17

将其添加到您的 EditText 中:

android:autoLink="web"
android:linksClickable="true"

Add this to your EditText:

android:autoLink="web"
android:linksClickable="true"
满意归宿 2024-09-06 07:35:17

使用 setMovementMethod(LinkMovementMethod.getInstance())Html.fromHTML( 时,请务必不要使用 setAutoLinkMask(Linkify.ALL) ) 位于格式正确的 HTML 链接上(例如 Google)。

Be sure to not use setAutoLinkMask(Linkify.ALL) when using setMovementMethod(LinkMovementMethod.getInstance()) and Html.fromHTML() on properly formatted HTML links (for example, <a href="http://www.google.com/">Google</a>).

对你而言 2024-09-06 07:35:17

使用这个...

TextView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent in=new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.twitter.com/"));
                        startActivity(in);
                    }
                    
                });

并在清单文件中添加权限:

<uses-permission android:name="android.permission.INTERNET"/>

Use this...

TextView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent in=new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.twitter.com/"));
                        startActivity(in);
                    }
                    
                });

And add a permission in the manifest file:

<uses-permission android:name="android.permission.INTERNET"/>
孤千羽 2024-09-06 07:35:17

您只需要这样:

android:autoLink="web"

将此行插入到可通过网络引用单击的 TextView 中。 URL 设置为该 TextView 的文本。

例子:

 <TextView
    android:id="@+id/textViewWikiURL"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textStyle="bold"
    android:text="http://www.wikipedia.org/"
    android:autoLink="web" />

You need only this:

android:autoLink="web"

Insert this line into a TextView that can be clickable with a reference to the web. The URL is set as a text of this TextView.

Example:

 <TextView
    android:id="@+id/textViewWikiURL"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:textStyle="bold"
    android:text="http://www.wikipedia.org/"
    android:autoLink="web" />

这就是我解决 TextView 中可点击和可见链接的方法(通过代码)

private void setAsLink(TextView view, String url){
    Pattern pattern = Pattern.compile(url);
    Linkify.addLinks(view, pattern, "http://");
    view.setText(Html.fromHtml("<a href='http://" + url + "'>http://" + url + "</a>"));
}

This is how I solved clickable and visible links in a TextView (by code)

private void setAsLink(TextView view, String url){
    Pattern pattern = Pattern.compile(url);
    Linkify.addLinks(view, pattern, "http://");
    view.setText(Html.fromHtml("<a href='http://" + url + "'>http://" + url + "</a>"));
}
紧拥背影 2024-09-06 07:35:17

使用下面的代码:

String html = "<a href=\"http://yourdomain.com\">Your Domain Name</a>"
TextView textview = (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(LinkMovementMethod.getInstance());
textview.setText(Html.fromHtml(html));

Use the below code:

String html = "<a href=\"http://yourdomain.com\">Your Domain Name</a>"
TextView textview = (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(LinkMovementMethod.getInstance());
textview.setText(Html.fromHtml(html));
滿滿的愛 2024-09-06 07:35:17

[在 Pre-lollipop 以及 Lollipop 及以上版本中测试]

您可以从后端或资源文件中获取 HTML 字符串。
如果您将文本作为资源字符串,请确保添加 CDATA 标记:

<string name="your_text">![CDATA[...<a href="your_link">Link Title</a>  ...]]</string>

然后在代码中您需要获取该字符串并将其分配为 HTML 并设置链接移动方法:

String yourText = getString(R.string.your_text);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
   textView.setText(Html.fromHtml(yourText, Html.FROM_HTML_MODE_COMPACT));
} else {
   textView.setText(Html.fromHtml(yourText));
}

try {
   subtext.setMovementMethod(LinkMovementMethod.getInstance());
} catch (Exception e) {
   //This code seems to crash in some Samsung devices.
   //You can handle this edge case base on your needs.
}

[Tested in Pre-lollipop as well as in Lollipop and above]

You can get your HTML string from the backend or from your resources files.
If you put your text as an resource string, make sure to add the CDATA tag:

<string name="your_text">![CDATA[...<a href="your_link">Link Title</a>  ...]]</string>

Then in code you need to get the string and assign it as HTML and set a link movement method:

String yourText = getString(R.string.your_text);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
   textView.setText(Html.fromHtml(yourText, Html.FROM_HTML_MODE_COMPACT));
} else {
   textView.setText(Html.fromHtml(yourText));
}

try {
   subtext.setMovementMethod(LinkMovementMethod.getInstance());
} catch (Exception e) {
   //This code seems to crash in some Samsung devices.
   //You can handle this edge case base on your needs.
}
何处潇湘 2024-09-06 07:35:17

在 SpannableString 上创建一个扩展方法:

private fun SpannableString.setLinkSpan(text: String, url: String) {
    val textIndex = this.indexOf(text)
    setSpan(
        object : ClickableSpan() {
            override fun onClick(widget: View) {
                Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(url) }.also { startActivity(it) }
            }
        },
        textIndex,
        textIndex + text.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
}

使用它使 TextView 中的字符串可点击:

    myTextView.apply {
        movementMethod = LinkMovementMethod.getInstance()

        val googleUrl = "http://www.google.com"
        val microsoftUrl = "http://www.microsoft.com"

        val google = "Google"
        val microsoft = "Microsoft"

        val message = SpannableString("$google & $microsoft").apply {
            setLinkSpan(google, googleUrl)
            setLinkSpan(microsoft, microsoftUrl)
        }

        text = message
    }

享受吧!

输入图像描述这里

Create an extension method on SpannableString:

private fun SpannableString.setLinkSpan(text: String, url: String) {
    val textIndex = this.indexOf(text)
    setSpan(
        object : ClickableSpan() {
            override fun onClick(widget: View) {
                Intent(Intent.ACTION_VIEW).apply { data = Uri.parse(url) }.also { startActivity(it) }
            }
        },
        textIndex,
        textIndex + text.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )
}

Use it to make string in your TextView clickable:

    myTextView.apply {
        movementMethod = LinkMovementMethod.getInstance()

        val googleUrl = "http://www.google.com"
        val microsoftUrl = "http://www.microsoft.com"

        val google = "Google"
        val microsoft = "Microsoft"

        val message = SpannableString("$google & $microsoft").apply {
            setLinkSpan(google, googleUrl)
            setLinkSpan(microsoft, microsoftUrl)
        }

        text = message
    }

Enjoy!

enter image description here

若沐 2024-09-06 07:35:17

您遇到问题的原因是它只尝试匹配“裸”地址。例如“www.google.com”或“http://www.google.com”。

通过 Html.fromHtml( ) 应该可以解决问题。您必须以编程方式执行此操作,但它确实有效。

The reason you're having the problem is that it only tries to match "naked" addresses. Things like "www.google.com" or "http://www.google.com".

Running your text through Html.fromHtml() should do the trick. You have to do it programmatically, but it works.

痴骨ら 2024-09-06 07:35:17

我不得不在几个地方寻找这个问题,但我终于让这个版本的代码可以工作。

文件strings.xml

<string name="name1"><a href="http://www.google.com">link text1</a></string>
<string name="name2"><a href="http://www.google.com">link text2</a></string>

文件myactivity.xml

<TextView
    android:id="@+id/textview1"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginTop="5dp" />

<TextView
    android:id="@+id/textview2"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginTop="5dp" />

文件myactivty.java(在onCreate()中):

TextView tv1 = (TextView)findViewById(R.id.textview1);
TextView tv2 = (TextView)findViewById(R.id.textview2);

tv1.setText(Html.fromHtml(getResources().getString(R.string.name1)));
tv2.setText(Html.fromHtml(getResources().getString(R.string.name2)));
tv1.setMovementMethod(LinkMovementMethod.getInstance());
tv2.setMovementMethod(LinkMovementMethod.getInstance());

这将创建两个可点击的超链接,其中text link text1link text2 将用户重定向至 Google。

I had to hunt this down in a couple places, but I finally got this version of the code to work.

File strings.xml:

<string name="name1"><a href="http://www.google.com">link text1</a></string>
<string name="name2"><a href="http://www.google.com">link text2</a></string>

File myactivity.xml:

<TextView
    android:id="@+id/textview1"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginTop="5dp" />

<TextView
    android:id="@+id/textview2"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginTop="5dp" />

File myactivty.java (in onCreate()):

TextView tv1 = (TextView)findViewById(R.id.textview1);
TextView tv2 = (TextView)findViewById(R.id.textview2);

tv1.setText(Html.fromHtml(getResources().getString(R.string.name1)));
tv2.setText(Html.fromHtml(getResources().getString(R.string.name2)));
tv1.setMovementMethod(LinkMovementMethod.getInstance());
tv2.setMovementMethod(LinkMovementMethod.getInstance());

This will create two clickable hyperlinks with the text link text1 and link text2 which redirect the user to Google.

一向肩并 2024-09-06 07:35:17

将 CDATA 添加到字符串资源

Strings.xml

<string name="txtCredits"><![CDATA[<a href=\"http://www.google.com\">Google</a>]]></string>

Add CDATA to your string resource

Strings.xml

<string name="txtCredits"><![CDATA[<a href=\"http://www.google.com\">Google</a>]]></string>
请恋爱 2024-09-06 07:35:17

如果使用基于 XML 的 TextView,则根据您的要求,您只需执行两件事:

  1. 在字符串中标识您的链接,例如“这是我的网页”。
    您可以将其添加到 XML 内容或代码中。

  2. 在具有 TextView 的 XML 内容中,添加以下内容:

     android:linksClickable="true"
    
     机器人:自动链接=“网络”
    

If using an XML-based TextView, for your requirement you need to do just two things:

  1. Identify your link in the string, such as "this is my WebPage."
    You can add it in the XML content or in the code.

  2. In the XML content that has the TextView, add these:

     android:linksClickable="true"
    
     android:autoLink="web"
    
北笙凉宸 2024-09-06 07:35:17

我只是浪费了很多时间来弄清楚你必须使用 getText(R.string.whatever) 而不是 getString(R.string.whatever)...

无论如何,这就是我的工作方式。同一文本视图中也有多个超链接。

TextView termsTextView = (TextView) getActivity().findViewById(R.id.termsTextView);
termsTextView.append("By registering your account, you agree to our ");
termsTextView.append(getText(R.string.terms_of_service));
termsTextView.append(", ");
termsTextView.append(getText(R.string.fees));
termsTextView.append(", and the ");
termsTextView.append(getText(R.string.stripe_connected_account_agreement));

termsTextView.setMovementMethod(LinkMovementMethod.getInstance());

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/termsTextView"/>

字符串示例:

    <string name="stripe_connected_account_agreement"><a href="https://stripe.com/connect/account-terms">Stripe Connected Account Agreement</a></string>

I just wasted so much time to figure out you have to use getText(R.string.whatever) instead of getString(R.string.whatever)...

Anyway, here is how I got mine working. With multiple hyperlinks in the same text view too.

TextView termsTextView = (TextView) getActivity().findViewById(R.id.termsTextView);
termsTextView.append("By registering your account, you agree to our ");
termsTextView.append(getText(R.string.terms_of_service));
termsTextView.append(", ");
termsTextView.append(getText(R.string.fees));
termsTextView.append(", and the ");
termsTextView.append(getText(R.string.stripe_connected_account_agreement));

termsTextView.setMovementMethod(LinkMovementMethod.getInstance());

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/termsTextView"/>

String example:

    <string name="stripe_connected_account_agreement"><a href="https://stripe.com/connect/account-terms">Stripe Connected Account Agreement</a></string>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文