klinker24 / Android-TextView-LinkBuilder

Insanely easy way to define clickable links within a TextView.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Regular expression useless

fraborna opened this issue · comments

there are several same strings and i just want turn one of them into clickable.
but the regular expression turns out useless(i have verify that the regular expression is right).
after reading the source code, i found the problem.

when meeting a link that contains a pattern, you convert it into a individual link by calling method turnPatternsToLinks().
but after calling that method, some information that the regular expression takes lost, such as the first string that matches or the last one.

for example, for text "fraborna likes fraborna's car", the regular expression "^fraborna" matches the first fraborna, but after call method turnPatternsToLinks(), the link contains pattern just becomes the same as the link contains string "fraborna".

here is my solution, and it seems to work

in the LinkBuilder, method build(), remove the turnPatternsToLinks() call, do not need to turn links contain patterns into normal links
and in method addLinkToSpan(Spannable s, Link link), i change it like this

   private void addLinkToSpan(Spannable s, Link link) {
        // get the current text
        String text = textView.getText().toString();
        Pattern pattern;
        if (link.getText() != null)
            pattern = Pattern.compile(Pattern.quote(link.getText()));
        else
            pattern = link.getPattern();
        Matcher matcher = pattern.matcher(text);

        // find one or more links inside the text
        while (matcher.find()) {

            // find the start and end point of the linked text within the TextView
            int start = matcher.start();

            //int start = text.indexOf(link.getText());
            if (start >= 0) {
                int end = start + matcher.group().length();

                // add link to the spannable text
                applyLink(link, new Range(start, end), s);
            }
        }
    }

1e661b2

Doesn't this commit do just that?

but it seems not to work.
the example i took showed that.
i just want the first "fraborna" to be clickable, but it will turn both "fraborna" into clickable.
so i adjust the code and it works, every pattern could be matched.

Wait, I guess i don't understand, if you are matching a regular expression, then they should all be clickable, not just the first instance. That commit made it so they were all clickable, which is the desired functionality.

If you just want one, then you should use Link without a regular expression. You could apply your code within your own app to find the first instance of the match, then turn the individual word into a clickable link.