Reputation: 27
I have the bellow code:
SpannableString ss = new SpannableString("Translators");
ClickableSpan myClickableSpan = new ClickableSpan()
{
@Override
public void onClick(View v) {
// do something;
}
};
ss.setSpan(myClickableSpan, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
But when i add the SpannableString into a String is unclickable and not underline
String thanks="Also thanks the "+ss;
Any ideas?
Upvotes: 0
Views: 1942
Reputation: 17444
This line is the problem:
String thanks="Also thanks the "+ss;
The right-hand side of the +
expression is a spannable string, the left hand side is a regular string (with no spanning support). The +
operator on strings causes the Java compiler to just put .toString()
after your ss
variable (in a null-safe way), and converting the spannable string to a normal string discards the spans.
To fix it, get rid of the string concatenation. You could use SpannableStringBuilder
in place of SpannableString
, and use the insert(...)
method to put the "Also thanks to the"
in there without losing the spans.
There's a simpler way though, your question code came quite close:
SpannableString ss = new SpannableString("Also thanks to the Translators");
ClickableSpan myClickableSpan = new ClickableSpan() { /*...*/ };
int spanStart = 20; // length of "Also thanks to the "
ss.setSpan(myClickableSpan, spanStart, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Upvotes: 4