Tunahan Bayındır Tunahan Bayındır - 3 months ago 27
Android Question

I can't get setSpan working

I have an string for e.g: "@user liked your photo! 2h ago" in thin typeface.

This string consists of 3 parts;

1: @user -> it should be typeface.normal and clickable

2: liked your photo! -> this stays the same (thin and black colored)

3: 2h ago -> this should be colored gray.

Spannable spannedTime = new SpannableString(time);
Spannable clickableUsername = new SpannableString(username);
clickableUsername.setSpan(new StyleSpan(Typeface.NORMAL), 0, clickableUsername.length(), 0); // this is for 1st part to make it normal typeface
spannedTime.setSpan(new BackgroundColorSpan(Color.GRAY), 0, spannedTime.length(), 0); // this is for 3rd part to make it gray

clickableUsername.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
CallProfileActivity();
}
}, 0, clickableUsername.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);// this is for 1st part to make it clickable

this.setText(clickableUsername + " " + notificationBody + " " + spannedTime);


But none of them has any effects.

Answer

The java compiler doesn't know about Spannable. When you do

this.setText(clickableUsername + " " + notificationBody + " " + spannedTime);

java creates a String concatination all the SpannableString.

To create a spannable string like you intent to do, you should use SpannableStringBuilder.

SpannableStringBuilder spannable = new SpannableStringBuilder();
spannable.append(clickableUsername, new StyleSpan(Typeface.NORMAL), 0);
spannable.append(' ').append(notificationBody).append(' ');
spannable.append(time, new BackgroundColorSpan(Color.GRAY), 0);
spannable.setSpan(new ClickableSpan() {
    @Override
    public void onClick(View view) {
        CallProfileActivity();
    }
}, 0, username.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
this.setText(spannable);