Issue
I making an app in which TextView
use a setText
from server.
So the string getting from server is dynamically change by user.
Now I want to make all words clickable from TextView
.
For example:
TextView return the text(string) is : cricket football hockey ...etc(whatever).
For this, I want to make each word clickable send the user to other activity for users like hashTag fashion in social media.
SpannableStringBuilder builder = new SpannableStringBuilder();
String[] words = tag.split(" ");
for(final String word: words)
{
builder.append(word).setSpan(new ClickableSpan()
{
@Override
public void onClick(@NonNull View view)
{
Toast.makeText(ClickPostEdit.this, word, Toast.LENGTH_SHORT).show();
}
// optional - for styling the specific text
/*@Override
public void updateDrawState(@NonNull TextPaint textPaint) {
textPaint.setColor(textPaint.linkColor); // you can use custom color
textPaint.setUnderlineText(false); // this remove the underline
}*/
}, builder.length() - word.length(), word.length(), 1);
}
EditPostTag.setText(builder, TextView.BufferType.SPANNABLE);
EditPostTag.setMovementMethod(LinkMovementMethod.getInstance());
Solution
Append ClickableSpans to a SpannbleStringBuilder.
You can iterate through your list of words, append each word to the builder and attach a ClickableSpan to it:
SpannableStringBuilder builder = new SpannableStringBuilder();
for(String word: words) {
builder
.append(word)
.setSpan(new ClickableSpan() {
@Override
public void onClick(@NonNull View view) {
// on click
}
// optional - for styling the specific text
/*@Override
public void updateDrawState(@NonNull TextPaint textPaint) {
textPaint.setColor(textPaint.linkColor); // you can use custom color
textPaint.setUnderlineText(false); // this remove the underline
}*/
}, builder.length() - word.length(), builder.length(), 0);
}
To set this Spannable to a TextView, use:
textView.setText(builder, TextView.BufferType.SPANNABLE);
textView.setMovementMethod(LinkMovementMethod.getInstance());
Taken from this post.
I hope you find my answer helpful!
Results:
Added ", " after each word
Answered By - ronginat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.