Skip to content

Instantly share code, notes, and snippets.

@patrickhammond
Created March 12, 2015 13:51
Show Gist options
  • Save patrickhammond/462b75f15df22838e5cc to your computer and use it in GitHub Desktop.
Save patrickhammond/462b75f15df22838e5cc to your computer and use it in GitHub Desktop.
Helper class that makes setting up links easier.
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.View.OnAttachStateChangeListener;
import android.widget.TextView;
public class TextViewHelper {
public static class LinkDetails {
public final String linkText;
// Just need an interface with a method I can call...
public final Runnable runnable;
public LinkDetails(String linkText, Runnable runnable) {
this.linkText = linkText;
this.runnable = runnable;
}
}
public static void setupLink(final TextView textView, String text, LinkDetails...linkDetails) {
final SpannableStringBuilder ssb = new SpannableStringBuilder(text);
for (final LinkDetails linkDetail : linkDetails) {
final ClickableSpan span = new ClickableSpan() {
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setColor(ds.linkColor);
}
@Override
public void onClick(final View widget) {
linkDetail.runnable.run();
// Without this you'll unpredictably have the actionable text selected with an annoying background.
Selection.removeSelection(((Spannable) ((TextView) widget).getText()));
}
};
int startOfLink = text.indexOf(linkDetail.linkText);
int linkLength = linkDetail.linkText.length();
ssb.setSpan(span, startOfLink, startOfLink + linkLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
textView.setText(ssb, TextView.BufferType.SPANNABLE);
textView.setLinkTextColor(textView.getResources().getColor(R.color.action_orange));
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setFocusable(false);
textView.setFocusableInTouchMode(false);
textView.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
}
@Override
public void onViewDetachedFromWindow(View v) {
// When this view gets detached I want to make sure any implicit references that came in on
// LinkDetails.runnable are cleared out.
textView.setText(null);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment