我无法让setSpan工作

时间:2016-08-08 22:32:18

标签: android spannablestring

我有一个字符串,例如:“@user like your photo!2h ago”in thin typeface。

此字符串由3部分组成;

1:@user - >它应该是typeface.normal和clickable

2:喜欢你的照片! - >这保持不变(薄和黑色)

3:2h ago - >这应该是灰色的。

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);

但它们都没有任何影响。

1 个答案:

答案 0 :(得分:2)

java编译器不了解Spannable。当你这样做

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

java创建String所有SpannableString的连接。

要像您想要的那样创建一个可跨越的字符串,您应该使用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);