2013-04-17 7 views
6

Mam problem z obiektem SpannableString.Dlaczego mój tekst nie wyświetla się ze stylem podczas używania SpannableStringBuilder?

Poniżej znajduje się krótki przykład:

SpannableString spanstr = new SpannableString("Bold please!"); 
spanstr.setSpan(new StyleSpan(Typeface.BOLD), 0, spanstr.length(), 0); 

SpannableStringBuilder sb = new SpannableStringBuilder(); 
sb.append(spanstr); 
sb.append("\n"); // A newline 
sb.append("The first line is bold. This one isn't."); 

CharSequence cq = sb.subSequence(0, sb.length()); 
// ^There's no such method to return a SpannableString, 
// so I try to return a CharSequence instead. 

// And then, at last: 
TextView contentView = (TextView) findViewById(R.id.some_id); 
contentView.setText(cq); 

Co przykładem próbuje zrobić to pokazano poniżej:

Bold proszę!
Pierwsza linia jest pogrubiona. Ten nie jest.

Ale problem polega na tym, że pierwsza linia tekstu nie jest pogrubiona.

Dlaczego tego nie robi?

+0

contentView.setText (sb); – Raghunandan

+0

Wypróbuj odpowiedź poniżej – Raghunandan

Odpowiedz

16

Użyj spannable ciąg konstruktora ustawiania jako tekst w TextView:

contentView.setText(sb); 

lub innego można zrobić tak:

SpannableStringBuilder spanstr = new SpannableStringBuilder("Bold please!"); 
spanstr.setSpan(new StyleSpan(Typeface.BOLD), 0, spanstr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
spanstr.append("\n"); 
spanstr.append("The first line is bold. This one isn't."); 
contentView.setText(spanstr); 
+0

Nie działa dla AlertDialog ... –

2

użycia samej instancji SpannableStringBuilder.

contentView.setText(sb); 

wyjście z kodem:

enter image description here

+0

Dziękuję bardzo. Nazwałem 'toString()' na 'spannableBuilder' i nie mogłem zrozumieć, dlaczego nie widziałem tekstów w stylu. –

+0

@RenatKaitmazov Nie powinieneś wywoływać metodyString() na SpannableBuilder, jeśli to zrobisz, potraktuje to jako String, a nie stylizowany tekst – Pragnani

2

Spróbuj poniżej. Musisz ustawić ciąg spannable do widoku tekstowego. Tak ustawić spannable ciąg tekstu, jak poniżej

String s= "The first line is bold. This one isn't"; 
String title="Bold Please!"; 
TextView tv = (TextView) findViewById(R.id.some_id); 
tv.setText(""); 
SpannableString ss1= new SpannableString(title); 
ss1.setSpan(new StyleSpan(Typeface.BOLD), 0, ss1.length(), 0); 
tv.append(ss1); 
tv.append("\n"); 
tv.append(s); 

Próbowałem powyżej można zobaczyć wynikowy zrzut poniżej.

enter image description here

+0

Dzięki .. Działa jak urok jako to, co chcę zaimplementować – KishuDroid

Powiązane problemy