Recently, I was working on an
EditText that supports links. That is, users can add URLs that become clickable when not editing.
EditText is not focused, the links should be clickable. However, when it is focused, it should disable the links so that the user can edit them without opening them.
It's simple enough to add an
OnFocusChangeListener for mode switching, but how does the user actually go about changing the focus (since clicking on the link would normally cause the browser to open)?
Long presses are one method. A second method should be to just click on any blank space in the
EditText, like so:
Unfortunately, due to the behavior of
LinkMovementMethod, if the last part of the text is a link, clicking anywhere causes the link to be opened.
My workaround hinged on the observation that this problem only happened if the last character of the text was a link. What if I added something after the text?
// Make links in the EditText clickable editText.setMovementMethod(LinkMovementMethod.getInstance()); // Setup my Spannable with clickable URLs Spannable spannable = new SpannableString("http://blog.danlew.net"); Linkify.addLinks(spannable, Linkify.WEB_URLS); // The fix: Append a zero-width space to the Spannable CharSequence text = TextUtils.concat(spannable, "\u200B"); // Use it! editText.setText(text);
Now clicking the empty space doesn't cause the link to be opened and I can switch into edit mode!