-1

There are a lot of answers about how to enable links in a TextView, but I couldn't find anything about how to make [a portion of] text in a TextView look like a link with a custom action. In other words I want to fake a link because the action isn't important enough to get a button. I don't want it to look like a main action on the page.

For example, in my about dialog I want to show the text "Open Source Licenses", have it look like a link, but launch my OpenSourceLicensesActivity instead of an actual URL.

I eventually got my answer from posts by those who were experiencing issues with the above, so I'm providing an answer to this specific question here.

copolii
  • 14,208
  • 10
  • 51
  • 80

1 Answers1

0

The method below will make the portion of the text from start to end clickable.

public static void makeClickableLink (@NonNull final TextView textView,
                                      @NonNull final CharSequence text,
                                      final int start,
                                      final int end,
                                      @NonNull final ClickableSpan onClick) { 
    final SpannableString span = new SpannableString (text);
    span.setSpan (onClick, start, end, 0);

    textView.setText (span);
    textView.setMovementMethod (LinkMovementMethod.getInstance ());
}

The provided ClickableSpan lets you handle the click event as such:

final TextView tv = (TextView)findViewById (android.R.id.text1);    

final ClickableSpan link = new ClickableSpan () {
    @Override public void onClick (final View widget) {
        context.startActivity (new Intent (context, OpenSourceLicensesActivity.class));
    }
};

makeClickableLink (tv, "Click here for OSS Licenses", 5, 9, link);

The above should makehere clickable, launching your activity.

copolii
  • 14,208
  • 10
  • 51
  • 80