Suraj Giri :
Suppose I have a string
String str =" Hello, @John how's going on"
Now I want to know., how to highlight the word @John
and wanna make it clickable from Textview
Santanu Sur :
You can use clickable span
in a spannable
string like the following :-
SpannableString ss = new SpannableString(" Hello, @John how's going on");
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
//perform click operation
}
@Override
public void updateDrawState(TextPaint ds) {
}
};
ss.setSpan(clickableSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTv.setText(ss);
yourTv.setMovementMethod(LinkMovementMethod.getInstance());
yourTv.setHighlightColor(Color.TRANSPARENT);
startIndex - is the index of J of word John in the full string
endIndex - is the index of n of the word John in the full string.
&& the onclick method will be triggered once john is clicked..
Edit
To extract the username John u can split the string and get it like this snippet :-
String username = yourString.split("@")[1].split(" ")[0]; // this will extract john