Skip to content

Instantly share code, notes, and snippets.

@daler445
Created January 27, 2021 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daler445/b7106b5c5ed431ecfb206afe98746bbe to your computer and use it in GitHub Desktop.
Save daler445/b7106b5c5ed431ecfb206afe98746bbe to your computer and use it in GitHub Desktop.
Dynamically create links in textview, android
#
# Credits: https://stackoverflow.com/a/45727769/2679982
#
TextView textView = view.findViewById(R.id.textview);
textView.setText("Dynamically created link");
List<Pair<String, View.OnClickListener>> links = new ArrayList<>();
links.add(new Pair<>(getString(R.string.auth_passport_confirm_agreement_link_label), new View.OnClickListener() {
@Override
public void onClick(View v) {
// on click ...
}
}));
Utils.makeLinks(textview, links);
#
# Credits: https://stackoverflow.com/a/45727769/2679982
#
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import java.util.List;
public class Utils {
public static void makeLinks(TextView textView, List<Pair<String, View.OnClickListener>> links) {
SpannableString spannableString = new SpannableString(textView.getText().toString());
int startIndexState = -1;
for (Pair<String, View.OnClickListener> link : links) {
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
widget.invalidate();
assert link.second != null;
link.second.onClick(widget);
}
};
assert link.first != null;
int startIndexOfLink = textView.getText().toString().indexOf(link.first, startIndexState + 1);
spannableString.setSpan(clickableSpan, startIndexOfLink, startIndexOfLink + link.first.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
}
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(spannableString, TextView.BufferType.SPANNABLE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment