Last active
September 10, 2019 06:02
-
-
Save duynhm/e5d9a09a4c390d98a628346396eb1e41 to your computer and use it in GitHub Desktop.
Spannable Click 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
private SpannableString addClickablePart2(String str) { | |
final SpannableString ss = new SpannableString(str); | |
final List<String> items = Arrays.asList(str.split("\\s*,\\s")); | |
int start = 0, end; | |
for (final String item : items) { | |
end = start + item.length(); | |
if (start < end) { | |
ss.setSpan(new ClickableSpan() { | |
@Override | |
public void onClick(View widget) { | |
Toast.makeText(MainActivity.this, item, | |
Toast.LENGTH_SHORT).show(); | |
} | |
}, start, end, 0); | |
} | |
start += item.length() + 2;//comma and space in the original text ;) | |
} | |
return ss; | |
} |
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
//click từng kí tự | |
private SpannableStringBuilder addClickablePart1(String str) { | |
SpannableStringBuilder ssb = new SpannableStringBuilder(str); | |
String[] array = str.split(" "); | |
int next = 0; | |
int start = 0; | |
for (final String s : array) { | |
start = str.indexOf(s, next); | |
ssb.setSpan(new NonUnderlinedClickableSpan() { | |
@Override | |
public void onClick(View widget) { | |
widget.setBackgroundColor(0xff0000); | |
widget.invalidate(); | |
// Toast.makeText(MainActivity.this, s, | |
// Toast.LENGTH_SHORT).show(); | |
tvText.setText(s); | |
} | |
}, start, next = start + s.length(), 0); | |
} | |
return ssb; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment