textview with multiple hyperlinks

2019-08-12 03:33发布

问题:

I have for example the following String

\n 3 Doors Down is a http://www.last.fm/tag/post-grunge\" class=\"bbcode_tag\" rel=\"tag\">post-grunge band from Escatawpa, Mississippi, United States, formed in 1996, consisting of Brad Arnold (vocals), Matt Roberts (guitars), Todd Harrell (bass), Chris Henderson (guitar), and Greg Upchurch (drums). The band signed to Universal Records in 2000 for their first album, http://www.last.fm/music/3+Doors+Down/The+Better+Life\" class=\"bbcode_album\">The Better Life. They received international attention with the release of the single "http://www.last.fm/music/3+Doors+Down/_/Kryptonite\" class=\"bbcode_track\">Kryptonite". The album went on to sell over 6 million copies. \n\n http://www.last.fm/music/3+Doors+Down\">Read more about 3 Doors Down on Last.fm.\n \n \nUser-contributed text is available under the Creative Commons By-SA License and may also be available under the GNU FDL.\n

I want to show the entire string in a textview with the hyperlinks clickable. I also don't want to see the actual url, just the text that's shown in place of the url. Reading other posts on the subject they all suggest defining a textview similar to this

<TextView
            android:id="@+id/tvArtistOverview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:autoLink="web"
            android:linksClickable="true" />

and setting the SetMovementMethod of the textview to

myTextView.setMovementMethod(LinkMovementMethod.getInstance());

When I follow these steps, my links are clickable, however they are not displayed as I wish. What am I missing?

Here is an example of how it currently looks.

回答1:

Use below code.

TextView tv = ....
tv.setMovementMethod(LinkMovementMethod.getInstance());

    String content = tv.getText().toString();
    List<String> links = new ArrayList<String>();

    Pattern p = Patterns.WEB_URL;
    Matcher m = p.matcher(content);
    while (m.find()) {
        String urlStr = m.group();
        links.add(urlStr);
    }

    SpannableString f = new SpannableString(content);

    for (int i = 0; i < links.size(); i++) {
        final String url = links.get(i);

        f.setSpan(new InternalURLSpan(new OnClickListener() {
            public void onClick(View v) {
                Context ctx = v.getContext();
                String urlToOpen = url;
                if (!urlToOpen.startsWith("http://") || !urlToOpen.startsWith("https://"))
                    urlToOpen = "http://" + urlToOpen;
                openURLInBrowser(urlToOpen, ctx);
            }
        }), content.indexOf(url), content.indexOf(url) + url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    tv.setText(f);