简体   繁体   English

如何使 TextView 中的链接可点击

[英]How to make links in a TextView clickable

I have the following TextView defined:我定义了以下 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"/>

where @string/txtCredits is a string resource that contains <a href="some site">Link text</a> .其中@string/txtCredits是包含<a href="some site">Link text</a>的字符串资源。

Android is highlighting the links in the TextView, but they do not respond to clicks. Android 突出显示 TextView 中的链接,但它们不响应点击。 What am I doing wrong?我究竟做错了什么? Do I have to set an onClickListener for the TextView in my activity for something as simple as this?我必须在我的活动中为 TextView 设置一个 onClickListener 吗?

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.这是一个遗憾,因为我宁愿显示一个文本链接而不是显示完整的 URL。

Buried in the API demos, I found the solution to my problem:埋在 API 演示中,我找到了解决我的问题的方法:

File Link.java :文件链接.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 上的大部分属性以匹配演示中的内容。

<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() .重要提示:如果您正在调用setMovementMethod()不要忘记删除autoLink="web"

I'm using only android:autoLink="web" and it works fine.我只使用android:autoLink="web"并且它工作正常。 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.在这种情况下,点击会转到此视图而不是链接。

After spending some time with this, I have found that:在花了一些时间之后,我发现:

  • android:autoLink="web" works if you have full links in your HTML. android:autoLink="web"如果您的 HTML 中有完整链接,则可以使用。 The following will be highlighted in blue and clickable:以下内容将以蓝色突出显示并可点击:
  • Some text <a href="http://www.google.com">http://www.google.com</a>一些文字<a href="http://www.google.com">http://www.google.com</a>
  • Some text http://www.google.com一些文字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>一些文字<a href="http://www.google.com">http://www.google.com</a>
  • Some text http://www.google.com一些文字http://www.google.com
  • Some text <a href="http://www.google.com">Go to Google</a>一些文字<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"与这样的联系工作。

  • android:autoLink="web" if set in XML will override view.setMovementMethod(LinkMovementMethod.getInstance()); android:autoLink="web"如果在 XML 中设置将覆盖view.setMovementMethod(LinkMovementMethod.getInstance()); (ie; links of the third kind will be highlighted, but not clickable). (即;第三类链接将突出显示,但不可点击)。

The moral of the story is use view.setMovementMethod(LinkMovementMethod.getInstance());这个故事的寓意是使用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.在您的代码中,如果您希望所有链接都可点击,请确保您的 XML 布局中没有android:autoLink="web"

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, ie:首先,在字符串资源中,使用 HTML 实体编码定义您的标签开口 V 形,即:

&lt;a href="http://www.google.com">Google&lt;/a>

And not :不是

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

In general, encode all the chevrons in the string like that.一般来说,像这样对字符串中的所有 V 形符号进行编码。 BTW, the link must start with http://顺便说一句,链接必须以http://开头

Then (as suggested here ) set this option on your TextView:然后(如建议在这里)设置你的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.不需要正则表达式或其他手动技巧。

I simply used this:我只是用这个:

Linkify.addLinks(TextView, Linkify.ALL);

It makes the links clickable, given here .它使链接可点击, 在此处给出。

If you want to add an HTML-like link, all you need to do is:如果你想添加一个类似 HTML 的链接,你需要做的就是:

  • add a resource HTML-like string:添加一个类似于 HTML 的资源字符串:

     <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:以编程方式将适当的 MovementMethod 添加到您的 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...是的,像“autoLink”和“linksClickable”这样的选项只处理显式链接(不包含在 HTML 标签中)对我来说也是非常误导......

The following should work for anyone who is looking for a combination of text and hyperlink within an Android app.以下内容适用于在 Android 应用程序中寻找文本和超链接组合的任何人。

In string.xml :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:现在你可以在任何给定的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"/>

Now, in your Activity or Fragment, do the following:现在,在您的 Activity 或 Fragment 中,执行以下操作:

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.到目前为止,您不需要使用这种方法设置android:autoLink="web"android:linksClickable="true"

I added this line to the TextView : android:autoLink="web"我将此行添加到TextViewandroid:autoLink="web"
Below is an example of usage in a layout file.以下是布局文件中的使用示例。

layout.xml sample 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:support@cleverfinger.com.au?Subject=Lost%20Password" target="_top">support@cleverfinger.com.au</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 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());

The easiest thing that worked for me was to use Linkify对我有用的最简单的方法是使用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.它会自动从 textview 中的文本中检测 web URL。

You only need to add this in the text view in XML:你只需要在 XML 的文本视图中添加这个:

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

Richard, next time, you should add this code under TextView at the layout XML instead.理查德,下次,您应该在布局 XML 的 TextView 下添加此代码。

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.您不需要使用此代码( t2.setMovementMethod(LinkMovementMethod.getInstance()); )来使链接可点击。

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.此外,事实是:只要您设置了autoLinklinksClickable ,请不要忘记在String.xml文件中添加它,以便可点击链接起作用。

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

By using linkify :通过使用linkify

Linkify takes a piece of text and a regular expression and turns all of the regex matches in the text into clickable links: Linkify接受一段文本和一个正则表达式,并将文本中的所有正则表达式匹配项转换为可点击的链接:

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;

Manage Linkify text color also还管理 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);

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.这是一个非常单行的 Android 代码,无论字符串和数据是什么,都可以从 textView 中选择电话和 URL。 You don't need to use any HTML tags for this.您不需要为此使用任何 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);

I noticed that using android:autoLink="web" thus我注意到使用android:autoLink="web"因此

<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 URL 工作正常,但由于我有一个电子邮件地址和电话号码,我也想链接,我最终使用了这一行android:autoLink="all"像这样

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

and it worked like a charm.它就像一个魅力。

The accepted answer is correct, but it will mean that phone numbers, maps, email addresses, and regular links, eg, http://google.com without href tags will no longer be clickable since you can't have an autolink in the XML content.接受的答案是正确的,但这意味着电话号码、地图、电子邮件地址和常规链接(例如,没有 href 标签的http://google.com不再可点击,因为您无法在XML 内容。

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 .而TextView中应该有android:autolink There's no need for android:linksClickable="true" either;也不需要android:linksClickable="true" it's true by default.默认情况下是真的。

You need only this:你只需要这个:

android:autoLink="web"

Insert this line into a TextView that can be clickable with a reference to the web.将此行插入到可通过引用 Web 进行点击的 TextView 中。 The URL is set as a text of this TextView. URL 设置为此 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" />

务必不要使用setAutoLinkMask(Linkify.ALL)使用时setMovementMethod(LinkMovementMethod.getInstance())Html.fromHTML()上正确格式HTML链接(例如, <a href="http://www.google.com/">Google</a> )。

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"/>

This is how I solved clickable and visible links in a TextView (by code)这就是我解决 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>"));
}

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));

[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.您可以从后端或资源文件中获取 HTML 字符串。 If you put your text as an resource string, make sure to add the CDATA tag:如果您将文本作为资源字符串,请确保添加CDATA标记:

<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:然后在代码中,您需要获取字符串并将其分配为 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.
}

I had to hunt this down in a couple places, but I finally got this version of the code to work.我不得不在几个地方找到它,但我终于让这个版本的代码可以工作。

File strings.xml :文件strings.xml

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

File myactivity.xml :文件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()):文件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());

This will create two clickable hyperlinks with the text link text1 and link text2 which redirect the user to Google.这将创建两个可点击的超链接,文本link text1link text2将用户重定向到 Google。

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".诸如“www.google.com”或“http://www.google.com”之类的东西。

Running your text through Html.fromHtml() should do the trick.通过Html.fromHtml()运行您的文本应该可以解决问题。 You have to do it programmatically, but it works.您必须以编程方式执行此操作,但它确实有效。

Add CDATA to your string resource将 CDATA 添加到您的字符串资源

Strings.xml字符串.xml

<string name="txtCredits"><![CDATA[<a href=\"http://www.google.com\">Google</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)...我只是浪费了很多时间来弄清楚你必须使用 getText(R.string.whatever) 而不是 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>

Autolink phone did not work for me. Autolink 电话对我不起作用。 The following worked like a charm,以下工作就像一个魅力,

TextView tv = (TextView) findViewById(R.id.emergencynos);
String html2="<br><br>Fire - <b><a href=tel:997>997</a> </b></br></br>";
tv.append(Html.fromHtml(html2));
tv.setMovementMethod(LinkMovementMethod.getInstance());

If using an XML-based TextView, for your requirement you need to do just two things:如果使用基于 XML 的 TextView,根据您的要求,您只需要做两件事:

  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.您可以将其添加到 XML 内容或代码中。

  2. In the XML content that has the TextView, add these:在具有 TextView 的 XML 内容中,添加以下内容:

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

Create an extension method on SpannableString:在 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:使用它使 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
    }

Enjoy!享受!

在此处输入图片说明

I have the following TextView defined:我定义了以下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"></TextView>

where @string/txtCredits is a string resource that contains <a href="some site">Link text</a> .其中@string/txtCredits是包含<a href="some site">Link text</a> @string/txtCredits <a href="some site">Link text</a>的字符串资源。

Android is highlighting the links in the TextView, but they do not respond to clicks. Android会突出显示TextView中的链接,但它们不会响应点击。 Can someone tell me what I'm doing wrong?有人可以告诉我我在做什么错吗? Do I have to set an onClickListener for the TextView in my activity for something as simple as this?我是否必须在我的活动中为TextView设置onClickListener,就像这样简单?

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.这真是令人讨厌,因为我宁愿显示文本链接也不显示完整的URL。

I have the following TextView defined:我定义了以下 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"></TextView>

where @string/txtCredits is a string resource that contains <a href="some site">Link text</a> .其中@string/txtCredits是包含<a href="some site">Link text</a> @string/txtCredits <a href="some site">Link text</a>的字符串资源。

Android is highlighting the links in the TextView, but they do not respond to clicks. Android 正在突出显示 TextView 中的链接,但它们不响应点击。 What am I doing wrong?我究竟做错了什么? Do I have to set an onClickListener for the TextView in my activity for something as simple as this?对于像这样简单的事情,我是否必须在我的活动中为 TextView 设置一个 onClickListener?

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.这是一个无赖,因为我宁愿显示一个文本链接而不是显示完整的 URL。

Use this:用这个:

package com.stackoverflow.java.android;

import android.content.Context;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.util.AttributeSet;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

public class HyperlinkTextView extends AppCompatTextView {
    public HyperlinkTextView(Context context) {
        super(context);
    }

    public HyperlinkTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public HyperlinkTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * Set default movement method to {@link LinkMovementMethod}
     * @return Link movement method as the default movement method
     */
    @Override
    protected MovementMethod getDefaultMovementMethod() {
        return LinkMovementMethod.getInstance();
    }
}

For those who are having issues with strings reading from XML content and assigning dynamically.对于那些从 XML 内容读取和动态分配字符串有问题的人。

In case you are using text from a strings.xml<\/em> resource, it seems that the HTML tags gets stripped out<\/strong> .如果您使用的是strings.xml<\/em>资源中的文本, HTML 标记似乎会被剥离<\/strong>。

So you have to use <![CDATA[**your string with click links**]]><\/code> in the strings.xml<\/em> file to convert it to HTML using Html.fromHtml(string)<\/strong> .因此,您必须在strings.xml<\/em>文件中使用<![CDATA[**your string with click links**]]><\/code>使用Html.fromHtml(string)<\/strong>将其转换为 HTML。

"

As the databinding is out, I'd like to share my solution for databinding TextViews supporting HTML tags with clickable links.随着数据绑定的发布,我想分享我的数据绑定 TextViews 解决方案,它支持带有可点击链接的 HTML 标记。

To avoid retrieving every textview and giving them html support using From.html we extend the TextView and put the logic in setText()为了避免检索每个 textview 并使用From.html为它们提供 html 支持,我们扩展了 TextView 并将逻辑放入setText()

public class HtmlTextView extends TextView {

    public HtmlTextView(Context context) {
        super(context);
    }

    public HtmlTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(Html.fromHtml(text.toString()), type);
        this.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

I've made a gist which also shows example entity and view for using this.我做了一个要点,它还显示了示例实体和使用它的视图。

Simply add this in your edittext只需将其添加到您的编辑文本中

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

if it doesn't work downvote my answer other wise 😉如果它不起作用,请以其他方式否决我的回答😉

You can simply add links to your TextView with Android's Linkify library .您可以使用 Android 的Linkify 库简单地将链接添加到 TextView。

Add to your strings.xml添加到您的字符串中。xml

<string name="text_legal_notice">By continuing, you confirm that you have read, understood and agreed to our %1$s and %2$s.</string>
<string name="text_terms_conditions">Terms &amp; Conditions</string>
<string name="text_privacy_policy">Privacy Policy</string>

Add to your activity添加到您的活动中

final String termsConditionsText = getString(R.string.text_terms_conditions);
final String privacyPolicyText = getString(R.string.text_privacy_policy);
final String legalText = getString(
        R.string.text_legal_notice,
        termsConditionsText,
        privacyPolicyText
);
viewBinding.textViewLegalNotice.setText(legalText);

Linkify.addLinks(
        viewBinding.textViewLegalNotice,
        Pattern.compile(termsConditionsText),
        null,
        null,
        (match, url) -> "https://policies.google.com/terms"
);
Linkify.addLinks(
        viewBinding.textViewLegalNotice,
        Pattern.compile(privacyPolicyText),
        null,
        null,
        (match, url) -> "https://policies.google.com/privacy"
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM