Created
January 27, 2021 12:31
-
-
Save daler445/b7106b5c5ed431ecfb206afe98746bbe to your computer and use it in GitHub Desktop.
Dynamically create links in textview, android
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
# | |
# 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); |
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
# | |
# 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