开发者

Linkify Android Transform Question

Trying to do something fairly simple.

Taking text like this

User Name: This is a comment I am making

It is in a single TextView. I want to make the User Name a link. I decided that the easiest thing would be to surround the User Name with something like "$@" so it becomes

"$@User Name:$@ This is a comment I am making

That way I can use the following regular expression

Pattern userName = Pattern.compile(".*\\$@(.+)\\$@.*");

with Linkify and make it a link. However, clear开发者_JS百科ly I need to remove the delimiters, so the following is the code

title.setText(titleText);
Linkify.TransformFilter transformer = new Linkify.TransformFilter() {

    @Override
    public String transformUrl(Matcher match, String url) {
       return match.group(1);
    }
};
Linkify.addLinks(title, userName, "content://user=", null,     transformer);

For some reason however, the whole text becomes one giant link, and the text isn't being transformed at all.


It actually did turned out to be pretty easy. I ended up not using the crazy "$@" to delimit the username, instead sticking with just

User Name: This is a comment I am making

so I ended up using the following pattern

Pattern userName = Pattern.compile("(.+:)");

Very simple, and the code becomes just

title.setText(titleText);
Linkify.addLinks(title, GlobalUtil.userName, "user://" + userId + "/");

Thank you to nil for the original suggestion. I was indeed matching the whole string instead of just the userName which is the link.


My best guess is the regex you're using is the problem, where you're telling it to basically pick out the entire string if it matches, including everything before and after what you're looking for. So, the TransformFilter is probably being passed the entire matched string. transformUrl as far as I can tell expects you to return the URL, so the entire string is linked to the first match group.

So, with that in mind, it's probably in your best interest to change the regex to something along the lines of "\\$@(.+?)\\$@" (with an added ? in the group to make the match non-greedy) so as to avoid matching the entire string and just picking out the bit you want to URL-ize (for lack of a better term, plus adding -ize to words sounds cool).


Why not put the delimiters inside the pattern to change ?

Pattern userName = Pattern.compile(".*(\\$@.+\\$@).*");

Then change the transform filter to remove the start and end patterns when changing into the URL...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜