2011-02-04 14 views
76

Sto cercando di cambiare il testo di una vista TextView tramite il metodo .setText ("") mentre coloriamo anche una parte del testo (o rendendolo grassetto, corsivo, trasparente, ecc.) E non il resto. Ad esempio:Android: colorare parte di una stringa usando TextView.setText()?

title.setText("Your big island <b>ADVENTURE!</b>"; 

So che il codice sopra riportato non è corretto ma aiuta a illustrare ciò che vorrei ottenere. Come lo farei?

+0

possibile duplicato di [come posso cambiare parte il colore di un TextView?] (Http://stackoverflow.com/questions/4032676/ how-can-i-change-color-part-of-a-textview) –

+0

Se c'è un testo lungo in TextView, c'è [un modo più efficiente] (http://stackoverflow.com/a/34449956/ 3414180) – Mingfei

+0

Possibile duplicato di [Imposta colore della spaziatura TextView in Android] (http://stackoverflow.com/questions/3282940/set-color-of-textview-span-in-android) – Suragch

risposta

177

Utilizzare spans.

Esempio:

final SpannableStringBuilder sb = new SpannableStringBuilder("your text here"); 

// Span to set text color to some RGB value 
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158)); 

// Span to make text bold 
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); 

// Set the text color for first 4 characters 
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

// make them also bold 
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

yourTextView.setText(sb); 
+8

Non mi piace molto la soluzione offerta da Android qui, in quanto non funziona con il multi linguaggio in quanto non ho idea di quanti caratteri sono nelle mie parole. Attualmente sto cercando una soluzione in cui posso avere più span che posso allegare tutti a un TextView e poi sono messi insieme – philipp

+1

Il commento dice span per rendere il testo in grassetto, dovrebbe dire estensione per rendere il colore del testo? – Ryan

+8

@philipp se il tuo problema è quanti caratteri nella tua parola, usa il metodo length() sul tuo String o StringBuilder o qualunque sia lo –

4

Se si desidera utilizzare HTML, è necessario utilizzare TextView.setText(Html.fromHtml(String htmlString))

Se si vuole fare che spesso/più volte, si può avere uno sguardo a una classe (SpannableBuilder) ho scritto, come Html.fromHtml() non è molto efficiente (sta usando un grande apparato di parsing xml all'interno). È descritto in questo blog posting.

45
title.setText(Html.fromHtml("Your big island <b>ADVENTURE!</b>")); 
+2

Questa è una soluzione molto più interessante del problema originale rispetto alla risposta contrassegnata. . – BSnapZ

+1

Se si verificano interruzioni di riga \ n, questo non visualizza le interruzioni di riga. –

+6

No, non è più bello, non c'è la funzione di colorazione, menzionato in questione ma il metodo SLOW da HTML() –

7

È possibile utilizzare uno Spannable per assegnare determinati aspetti di un testo. Posso cercare un esempio, se vuoi.

Ah, da qui su stackoverflow.

TextView TV = (TextView)findViewById(R.id.mytextview01); 
Spannable WordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");   
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
TV.setText(WordtoSpan); 
22

Spero che questo ti aiuta (funziona con multi lingua).

<string name="test_string" ><![CDATA[<font color="%1$s"><b>Test/b></font>]]> String</string> 

E sul codice Java, si può fare:

int color = context.getResources().getColor(android.R.color.holo_blue_light); 
String string = context.getString(R.string.test_string, color); 
textView.setText(Html.fromHtml(string)); 

In questo modo, solo la parte "Test" sarà colorato (e in grassetto).

+3

Risposta migliore. Funziona perfettamente per stringhe internazionali. Ha anche il vantaggio di poter avere il testo colorato nel mezzo della risorsa stringa. –

+0

Per ulteriori spiegazioni, consultare la sezione ** Styling con HTML markup ** [qui] (http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling). – Elisa

16

Ecco un esempio che potete trovare tutte le occorrenze di una parola (case insensitive), e di colore rosso:

String notes = "aaa AAA xAaax abc aaA xxx"; 
SpannableStringBuilder sb = new SpannableStringBuilder(notes); 
Pattern p = Pattern.compile("aaa", Pattern.CASE_INSENSITIVE); 
Matcher m = p.matcher(notes); 
while (m.find()){ 
    //String word = m.group(); 
    //String word1 = notes.substring(m.start(), m.end()); 

    sb.setSpan(new ForegroundColorSpan(Color.rgb(255, 0, 0)), m.start(), m.end(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); 
} 
editText.setText(sb); 
+0

Mi piace il tuo nome: P Posso cambiare lo sfondo di una parola specifica con il nuovo BackgroundColorSpan (Color.parseColor ("# BFFFC6"))? –

1

È possibile concatenare due o più campate. In questo modo è più facile colorare il testo dinamico usando il valore della lunghezza.

SpannableStringBuilder span1 = new SpannableStringBuilder("Android"); 
ForegroundColorSpan color1=new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)); 
span1.setSpan(color1, 0, span1.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

SpannableStringBuilder span2 = new SpannableStringBuilder("Love"); 
ForegroundColorSpan color2=new ForegroundColorSpan(getResources().getColor(R.color.colorSecondary)); 
span2.setSpan(color2, 0, span2.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

Spanned concatenated=(Spanned) TextUtils.concat(span1," => ",span2); 

SpannableStringBuilder result = new SpannableStringBuilder(concatenated); 

TextView tv = (TextView) rootView.findViewById(R.id.my_texview); 
tv.setText(result, TextView.BufferType.SPANNABLE); 
1

Usa questo codice sua utile

TextView txtTest = (TextView) findViewById(R.id.txtTest); 
txtTest.setText(Html.fromHtml("This is <font color="#ff4343">Red</font> Color!")); 
1

  String str1 = "If I forget my promise to "; 
 
      String penalty = "Eat breakfast every morning,"; 
 
      String str2 = " then I "; 
 
      String promise = "lose my favorite toy"; 
 
      
 

 
      String strb = "<u><b><font color='#081137'>"+ penalty +",</font></b></u>"; 
 
      String strc = "<u><b><font color='#081137'>"+ promise + "</font></b></u>"; 
 
      String strd = str1 +strb+ str2 + strc; 
 
      tv_notification.setText(Html.fromHtml(strd));

o di questo codice:

SpannableStringBuilder builder = new SpannableStringBuilder(); 
 
      SpannableString text1 = new SpannableString(str1); 
 
      text1.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.silver)), 0, str1.length() - 1, 0); 
 
      builder.append(text1); 
 

 
      SpannableString text2 = new SpannableString(penalty); 
 
      text2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.midnight)), 0, penalty.length(), 0); 
 
      text2.setSpan(new UnderlineSpan(), 0, penalty.length(), 0); 
 
      builder.append(text2); 
 

 
      SpannableString text3 = new SpannableString(str2); 
 
      text3.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.silver)),0, str2.length(), 0); 
 
      builder.append(text3); 
 

 

 
      SpannableString text4 = new SpannableString(promise); 
 
      text4.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.midnight)), 0, promise.length(), 0); 
 
      text4.setSpan(new UnderlineSpan(),0, promise.length(), 0); 
 
      builder.append(text4); 
 

 
      tv_notification.setText(builder);

1
public static void setColorForPath(Spannable spannable, String[] paths, int color) { 
    for (int i = 0; i < paths.length; i++) { 
     int indexOfPath = spannable.toString().indexOf(paths[i]); 
     if (indexOfPath == -1) { 
      return; 
     } 
     spannable.setSpan(new ForegroundColorSpan(color), indexOfPath, 
       indexOfPath + paths[i].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    } 
} 

Utilizzando

Spannable spannable = new SpannableString("Your big island ADVENTURE"); 
Utils.setColorForPath(spannable, new String[] { "big", "ADVENTURE" }, Color.BLUE); 

textView.setText(spannable); 

enter image description here

Problemi correlati