2016-08-08 13 views
0

Ich habe eine Zeichenfolge für z. B.: "@ user mochte Ihr Foto! Vor 2 Stunden" in dünne Schrift.Ich kann nicht setSpan funktioniert

Diese Zeichenfolge besteht aus 3 Teilen;

1: -: gemocht Ihr Foto @user> es typeface.normal und klickbare

2 sein sollte! -> das bleibt gleich (dünn und schwarz)

vor 3: 2h -> das sollte grau sein.

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

Aber keiner von ihnen hat irgendwelche Auswirkungen.

+0

Definieren Sie "nicht funktioniert" ... Was macht 'CallProfileActivity();' tun? –

+0

siehe BackgroundColorSpan, StyleSpan und ClickableSpan, keiner von ihnen funktioniert. CallProfileActivity(); funktioniert ganz richtig, es öffnet nur eine Aktivität. –

+0

Könnten Sie bitte ein [mcve] bereitstellen, damit wir versuchen könnten, das Problem zu reproduzieren? –

Antwort

2

Der Java-Compiler weiß nicht über Spannable. Wenn Sie

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

tun schafft java eine String Verketten alle SpannableString.

Um eine spannbare Zeichenfolge zu erstellen, wie Sie beabsichtigen, sollten Sie SpannableStringBuilder verwenden.

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