Last active
October 1, 2015 19:24
-
-
Save aguestuser/50c8401b3440f793bf60 to your computer and use it in GitHub Desktop.
Wrapper around Android's `Linkfy` class for wrapping substrings of strings with hyperlinks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.text.SpannableString; | |
import android.text.util.Linkify; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class Text { | |
// takes arbitrary string and wraps arbitrary substring with an arbtitrary URL | |
public static SpannableString linkify(String txt, String linkTxt, String scheme, String url) { | |
SpannableString s = new SpannableString(txt); | |
boolean yup = Linkify.addLinks( | |
s, Pattern.compile(linkTxt), scheme, | |
new Linkify.MatchFilter(){ | |
@Override | |
public boolean acceptMatch(CharSequence c, int s, int e){ | |
return true; | |
} | |
}, | |
new Linkify.TransformFilter(){ | |
@Override | |
public String transformUrl(Matcher match, String baseUrl) { | |
return url; | |
} | |
} | |
); | |
if(yup) return s; | |
else return null; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.tlc.whereat.util; | |
import android.text.Spannable; | |
import android.text.SpannableString; | |
import android.text.TextUtils; | |
import android.text.style.URLSpan; | |
import static org.junit.Assert.*; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.robolectric.RobolectricGradleTestRunner; | |
import org.robolectric.annotation.Config; | |
import org.tlc.whereat.BuildConfig; | |
import java.util.ArrayList; | |
import java.util.List; | |
import static org.assertj.core.api.Assertions.*; | |
/** | |
* Author: @aguestuser | |
* License: GPLv3 (https://www.gnu.org/licenses/gpl-3.0.html) | |
*/ | |
@RunWith(RobolectricGradleTestRunner.class) | |
@Config(constants = BuildConfig.class, sdk = 21) | |
public class TextTest { | |
@Test | |
public void linkify_should_addALinkToASubstring(){ | |
SpannableString res = | |
Text.linkify("Please visit our homepage.","our homepage.", "https://", "whereat.io"); | |
URLSpan[] spans = res.getSpans(0, res.length(), URLSpan.class); | |
String link = spans[0].getURL(); | |
assertThat(res.toString()).isEqualTo("Please visit our homepage."); | |
assertThat(spans.length).isEqualTo(1); | |
assertThat(link).isEqualTo("https://whereat.io"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment