简体   繁体   中英

Click on Link in TextView

I have some text with a link in a TextView. Now I want that the browser open the link if the user click on it. My TextView looks like this:

<string name="Info">Go to <a href="www.google.com">Google</a></string>

<TextView
        android:id="@+id/Info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/OptionMarginBottom"
        android:autoLink="web"
        android:linksClickable="true"
        android:text="@string/Info" />

The Link is displayed correct in blue but I can not click on it. Why is that?

use this method

public static void addLink(TextView textView, String patternToMatch,
        final String link) {
    Linkify.TransformFilter filter = new Linkify.TransformFilter() {
        @Override public String transformUrl(Matcher match, String url) {
            return link;
        }
    };
    Linkify.addLinks(textView, Pattern.compile(patternToMatch), null, null,
            filter);
}

and use as

addLink(text, "^Android", "http://abhiandroidinfo.blogspot.in");

Use Linkify on your TextView

Linkify.addLinks(yourTextviewObject, Linkify.WEB_URLS);

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

Helper Method:

public static void addLinks(TextView textView, String linkThis, String toThis) {
        Pattern pattern = Pattern.compile(linkThis);
        String scheme = toThis;
        android.text.util.Linkify.addLinks(textView, pattern, scheme, new MatchFilter() {
            @Override
            public boolean acceptMatch(CharSequence s, int start, int end) {
                return true;
            }
        }, new TransformFilter() {

            @Override
            public String transformUrl(Matcher match, String url) {
                return "";
            }
        });
    }

Now use like Below:

String weblink = "WebsiteName";
String url = course.getString(TAG_Info);

TextView txtInfo= (TextView) findViewById(R.id.Info);
txtInfo.setText(userCanSeeThis);

addLinks(txtInfo, weblink, url);

Easier method is to make a string and add Link Text and in the xml file, make the textView:

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autoLink="web"
    android:text="@string/string_with_link" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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