如何在可点击的TextView中创建链接?

时间:2022-02-13 06:56:54

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是一个字符串资源,它包含链接文本

Android is highlighting the links in the TextView, but they do not respond to clicks. 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?

Android在TextView中突出显示链接,但是他们不响应点击。有人能告诉我我做错了什么吗?我是否需要在我的活动中为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。

31 个解决方案

#1


1076  

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

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

Link.java:

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上的大部分属性,以匹配演示中的属性。

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

That solved it. Pretty difficult to uncover and fix.

解决它。很难发现和修复。

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

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

#2


456  

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

我只使用android:autoLink="web",运行良好。点击链接将打开浏览器并显示正确的页面。

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.

我能猜到的一件事是,在链接之上还有其他的视图。透明的内容会填充整个父元素,但不会显示链接之上的任何内容。在本例中,单击将转到该视图,而不是链接。

#3


288  

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:
  • 如果在HTML中有完整的链接,那么autoLink=“web”可以工作。以下将以蓝色突出显示,可点击:
  • Some text <a href="http://www.google.com">http://www.google.com</a>
  • 一些文本http://www.google.com < a href = " http://www.google.com " > < / >
  • Some text http://www.google.com
  • 一些文本http://www.google.com
  • view.setMovementMethod(LinkMovementMethod.getInstance()); will work with the following (will be highlighted and clickable):
  • view.setMovementMethod(LinkMovementMethod.getInstance());将与以下工作(将突出显示并可点击):
  • Some text <a href="http://www.google.com">http://www.google.com</a>
  • 一些文本http://www.google.com < a href = " http://www.google.com " > < / >
  • Some text http://www.google.com
  • 一些文本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"不支持这种链接。

  • 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).
  • android:autoLink=“web”,如果设置为XML,将覆盖view.setMovementMethod(LinkMovementMethod.getInstance());(即。将突出显示第三种链接,但不能单击)。

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.

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

#4


84  

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.:

上面的解决方案对我不起作用,但是下面的解决方案对我起了作用(它看起来更干净一些)。首先,在字符串资源中,使用HTML实体编码定义标签打开的chevrons,即:

&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. BTW, the link must start with http://

一般来说,对字符串中的所有chevrons编码都是这样的。顺便说一句,链接必须以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 regexes or other manual hacks required.

就是这样,不需要任何regex或其他手工操作。

#5


56  

If you want to add 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 appropriate MovementMethod programmatically to your TextView:

    以编程方式向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...

就是这样!是的,像“自动链接”和“链接可链接”这样的选项只用于显式链接(不包含在html标签中)对我来说也非常具有误导性……

#6


55  

i used this simply

我用这个简单的

Linkify.addLinks(TextView, Linkify.ALL);

makes the links clickable given here

使链接可点击这里

#7


40  

I added this line to the TextView: android:autoLink="web"
Below is an example of usage in a layout file.

我在TextView中添加了这一行:android:autoLink="web"是布局文件中使用的一个例子。

layout.xml sample

布局。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.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>

#8


22  

Only what do you need to add this in text view in xml

只需要在xml的文本视图中添加什么

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

#9


22  

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

#10


18  

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

Richard,下次你应该把这个代码添加到TextView的布局XML中。

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.

还有,这是事实:只要你设置了自动链接和链接链接,不要忘记在字符串中添加这个。xml文件,以便可点击链接工作。

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

#11


14  

The easiest thing that worked for me is 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。

#12


13  

by using linkify: Linkify take a piece of text and a regular expression and turns all of the regex matches in the text into clickable links

通过使用linkify: linkify获取一段文本和一个正则表达式,并将文本中的所有regex匹配项转换为可单击链接

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

Don't forget to

别忘了

import android.widget.TextView;

#13


12  

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.

它就像一种魔力。

#14


11  

Here is very one line android code to make phone and url selectable from textView no matter what is string and what is data. You dont need to use any HTML tags for this.

这里有一行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);

#15


11  

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

当使用setMovementMethod(LinkMovementMethod.getInstance())和HTML . fromhtml()时,请确保不要使用setAutoLinkMask(Linkify.ALL),并使用正确格式化的HTML链接(例如,谷歌)。

#16


8  

You need only this:

你只需要:

android:autoLink="web"

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

将这一行插入到TextView中,可以根据web进行单击。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" />

#17


8  

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 autolink in the xml.

公认的答案是正确的,但这将意味着没有href标记的电话号码、地图、电子邮件地址和常规链接(例如http://google.com)将不再可点击,因为您不能在xml中使用autolink。

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.

TextView不应该有android:autolink。也不需要android:linksClickable="true";在默认情况下这是真的。

#18


7  

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

#19


7  

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 permission in manifest file

并在manifest文件中添加权限

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

#20


6  

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

#21


6  

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 the regular Zesteve App? 
<a href="https://play.google.com/store/apps/details?id=zesteve.com.myapplication">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.

现在,您不需要使用这种方法设置android:autoLink="web"或android:linksClickable="true"。

I hope you will find this helpful.

我希望你会觉得这对你有帮助。

#22


5  

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. You have to do it programatically, but it works.

通过Html.fromHtml()运行您的文本应该可以达到这个目的。你必须按程序来做,但它是有效的。

#23


4  

Autolink phone does not worked for me. The following worked like a charm,

Autolink手机对我没用。下面这句话很有魅力,

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

#24


4  

Add CDATA to your string resource

将CDATA添加到字符串资源中

Strings.xml

Strings.xml

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

#25


3  

Don't know if it's worth adding another answer, but just in case...

不知道是否值得再加一个答案,但以防万一……

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

我不得不在几个地方查找它,但最终让这个版本的代码起作用。

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>

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

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.

这将创建两个可点击的超链接,文本链接text1和链接text2,将用户重定向到谷歌。

#26


3  

If using 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 xml or in the code.

    在字符串中标识你的链接,比如“这是我的网页”。您可以在xml或代码中添加它。

  2. In the xml that has the TextView, add these:

    在具有TextView的xml中,添加以下内容:


android:linksClickable="true"

android:autoLink="web"

#27


3  

I use the autolink to "auto underline" the text, but just made an "onClick" that manages it. (I ran into this problem myself)

我使用autolink来“自动下划线”文本,但只是做了一个“onClick”来管理它。(我自己也遇到了这个问题)

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:textSize="18dp"
            android:autoLink="all"
            android:text="@string/twitter"
            android:onClick="twitter"/>

public void twitter (View view)
    {
        try
        {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://twitter.com/onaclovtech"));
            startActivity(browserIntent);

        }
        finally
        {
        }
    }

Doesn't require any permissions, as you are passing the intent off to apps that manage those resources, (I.E. browser).

不需要任何权限,因为您将意图传递给管理这些资源的应用程序(例如浏览器)。

This was what worked for me. Good luck.

这对我起了作用。祝你好运。

#28


1  

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

只是浪费了太多的时间去弄明白你必须使用getText(r . str.whatever)而不是getString(r . str.whatever)……

Anyways, 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>

#29


1  

My code was like this:

我的代码是这样的:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/link"
    android:text="@string/forgot"
    android:layout_marginTop="16dp"
    android:gravity="center"
    android:linksClickable="true"/>

My Java code was like this:

我的Java代码是这样的:

/*TextView action*/
        TextView textView = (TextView) findViewById(R.id.link);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,forgot.class));
            }
        });  

This just points the link to another activity. But that link is clickable and works smoothly. Tested in Android Studio 1.5 (Preview)

这只是指向另一个活动的链接。但是这个链接是可以点击的,并且工作顺利。在Android Studio 1.5中测试(预览)

#30


1  

[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:

可以从后端或资源文件中获取HTML字符串。如果将文本作为资源字符串,请确保添加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.
}

#1


1076  

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

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

Link.java:

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上的大部分属性,以匹配演示中的属性。

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

That solved it. Pretty difficult to uncover and fix.

解决它。很难发现和修复。

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

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

#2


456  

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

我只使用android:autoLink="web",运行良好。点击链接将打开浏览器并显示正确的页面。

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.

我能猜到的一件事是,在链接之上还有其他的视图。透明的内容会填充整个父元素,但不会显示链接之上的任何内容。在本例中,单击将转到该视图,而不是链接。

#3


288  

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:
  • 如果在HTML中有完整的链接,那么autoLink=“web”可以工作。以下将以蓝色突出显示,可点击:
  • Some text <a href="http://www.google.com">http://www.google.com</a>
  • 一些文本http://www.google.com < a href = " http://www.google.com " > < / >
  • Some text http://www.google.com
  • 一些文本http://www.google.com
  • view.setMovementMethod(LinkMovementMethod.getInstance()); will work with the following (will be highlighted and clickable):
  • view.setMovementMethod(LinkMovementMethod.getInstance());将与以下工作(将突出显示并可点击):
  • Some text <a href="http://www.google.com">http://www.google.com</a>
  • 一些文本http://www.google.com < a href = " http://www.google.com " > < / >
  • Some text http://www.google.com
  • 一些文本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"不支持这种链接。

  • 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).
  • android:autoLink=“web”,如果设置为XML,将覆盖view.setMovementMethod(LinkMovementMethod.getInstance());(即。将突出显示第三种链接,但不能单击)。

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.

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

#4


84  

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.:

上面的解决方案对我不起作用,但是下面的解决方案对我起了作用(它看起来更干净一些)。首先,在字符串资源中,使用HTML实体编码定义标签打开的chevrons,即:

&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. BTW, the link must start with http://

一般来说,对字符串中的所有chevrons编码都是这样的。顺便说一句,链接必须以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 regexes or other manual hacks required.

就是这样,不需要任何regex或其他手工操作。

#5


56  

If you want to add 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 appropriate MovementMethod programmatically to your TextView:

    以编程方式向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...

就是这样!是的,像“自动链接”和“链接可链接”这样的选项只用于显式链接(不包含在html标签中)对我来说也非常具有误导性……

#6


55  

i used this simply

我用这个简单的

Linkify.addLinks(TextView, Linkify.ALL);

makes the links clickable given here

使链接可点击这里

#7


40  

I added this line to the TextView: android:autoLink="web"
Below is an example of usage in a layout file.

我在TextView中添加了这一行:android:autoLink="web"是布局文件中使用的一个例子。

layout.xml sample

布局。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.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>

#8


22  

Only what do you need to add this in text view in xml

只需要在xml的文本视图中添加什么

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

#9


22  

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

#10


18  

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

Richard,下次你应该把这个代码添加到TextView的布局XML中。

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.

还有,这是事实:只要你设置了自动链接和链接链接,不要忘记在字符串中添加这个。xml文件,以便可点击链接工作。

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

#11


14  

The easiest thing that worked for me is 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。

#12


13  

by using linkify: Linkify take a piece of text and a regular expression and turns all of the regex matches in the text into clickable links

通过使用linkify: linkify获取一段文本和一个正则表达式,并将文本中的所有regex匹配项转换为可单击链接

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

Don't forget to

别忘了

import android.widget.TextView;

#13


12  

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.

它就像一种魔力。

#14


11  

Here is very one line android code to make phone and url selectable from textView no matter what is string and what is data. You dont need to use any HTML tags for this.

这里有一行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);

#15


11  

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

当使用setMovementMethod(LinkMovementMethod.getInstance())和HTML . fromhtml()时,请确保不要使用setAutoLinkMask(Linkify.ALL),并使用正确格式化的HTML链接(例如,谷歌)。

#16


8  

You need only this:

你只需要:

android:autoLink="web"

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

将这一行插入到TextView中,可以根据web进行单击。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" />

#17


8  

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 autolink in the xml.

公认的答案是正确的,但这将意味着没有href标记的电话号码、地图、电子邮件地址和常规链接(例如http://google.com)将不再可点击,因为您不能在xml中使用autolink。

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.

TextView不应该有android:autolink。也不需要android:linksClickable="true";在默认情况下这是真的。

#18


7  

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

#19


7  

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 permission in manifest file

并在manifest文件中添加权限

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

#20


6  

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

#21


6  

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 the regular Zesteve App? 
<a href="https://play.google.com/store/apps/details?id=zesteve.com.myapplication">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.

现在,您不需要使用这种方法设置android:autoLink="web"或android:linksClickable="true"。

I hope you will find this helpful.

我希望你会觉得这对你有帮助。

#22


5  

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. You have to do it programatically, but it works.

通过Html.fromHtml()运行您的文本应该可以达到这个目的。你必须按程序来做,但它是有效的。

#23


4  

Autolink phone does not worked for me. The following worked like a charm,

Autolink手机对我没用。下面这句话很有魅力,

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

#24


4  

Add CDATA to your string resource

将CDATA添加到字符串资源中

Strings.xml

Strings.xml

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

#25


3  

Don't know if it's worth adding another answer, but just in case...

不知道是否值得再加一个答案,但以防万一……

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

我不得不在几个地方查找它,但最终让这个版本的代码起作用。

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>

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

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.

这将创建两个可点击的超链接,文本链接text1和链接text2,将用户重定向到谷歌。

#26


3  

If using 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 xml or in the code.

    在字符串中标识你的链接,比如“这是我的网页”。您可以在xml或代码中添加它。

  2. In the xml that has the TextView, add these:

    在具有TextView的xml中,添加以下内容:


android:linksClickable="true"

android:autoLink="web"

#27


3  

I use the autolink to "auto underline" the text, but just made an "onClick" that manages it. (I ran into this problem myself)

我使用autolink来“自动下划线”文本,但只是做了一个“onClick”来管理它。(我自己也遇到了这个问题)

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:textSize="18dp"
            android:autoLink="all"
            android:text="@string/twitter"
            android:onClick="twitter"/>

public void twitter (View view)
    {
        try
        {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://twitter.com/onaclovtech"));
            startActivity(browserIntent);

        }
        finally
        {
        }
    }

Doesn't require any permissions, as you are passing the intent off to apps that manage those resources, (I.E. browser).

不需要任何权限,因为您将意图传递给管理这些资源的应用程序(例如浏览器)。

This was what worked for me. Good luck.

这对我起了作用。祝你好运。

#28


1  

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

只是浪费了太多的时间去弄明白你必须使用getText(r . str.whatever)而不是getString(r . str.whatever)……

Anyways, 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>

#29


1  

My code was like this:

我的代码是这样的:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/link"
    android:text="@string/forgot"
    android:layout_marginTop="16dp"
    android:gravity="center"
    android:linksClickable="true"/>

My Java code was like this:

我的Java代码是这样的:

/*TextView action*/
        TextView textView = (TextView) findViewById(R.id.link);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,forgot.class));
            }
        });  

This just points the link to another activity. But that link is clickable and works smoothly. Tested in Android Studio 1.5 (Preview)

这只是指向另一个活动的链接。但是这个链接是可以点击的,并且工作顺利。在Android Studio 1.5中测试(预览)

#30


1  

[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:

可以从后端或资源文件中获取HTML字符串。如果将文本作为资源字符串,请确保添加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.
}