Android Linkify A Completely Unrelated String

别来无恙 提交于 2019-12-12 02:09:06

问题


I want to do something like Click <a href='www.google.com'>Here</a>

in android. I tried using the following:

TextView sponsoredlink = new TextView(this);
                sponsoredlink.setId(R.id.details_sponsored_link);
                sponsoredlink.setText("Click Here");

                Pattern pattern =Pattern.compile("Here");

                String link = "www.google.com";

                Linkify.addLinks(sponsoredlink, pattern, link);

but i just end up with a link to www.google.comhere [sic]


回答1:


Just to answer my own question, I found a tutorial on transform filters and adapted it to my own ends:

TextView sponsoredlink = new TextView(this);
                sponsoredlink.setId(R.id.details_sponsoredlink);
                sponsoredlink.setText("Click Here");

                TransformFilter mentionFilter = new TransformFilter() {
                    public final String transformUrl(final Matcher match, String url) {
                        return new String("http://www.google.com");
                    }
                };

                // Match @mentions and capture just the username portion of the text.
                Pattern pattern = Pattern.compile(".");
                String scheme = "";
                Linkify.addLinks(sponsoredlink, pattern, scheme, null, mentionFilter);

I decided I wanted to turn the whole text into one big link in the end, so I did a pattern that matched the whole text.

Then I created a transform filter which just ignores whatever you give it and returns the URL I wanted to take people to

The scheme also has to be the empty string so nothing gets added on the end

Finally I used linkify to put it all together



来源:https://stackoverflow.com/questions/5249013/android-linkify-a-completely-unrelated-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!