2011-02-04 18 views
76

Estoy buscando cambiar el texto de una vista TextView mediante el método .setText ("") mientras coloreo una parte del texto (o lo hago en negrita, cursiva, transparente, etc.) y no el resto. Por ejemplo:Android: ¿Colorear parte de una cadena usando TextView.setText()?

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

Sé que el código anterior es incorrecto pero ayuda a ilustrar lo que me gustaría lograr. ¿Cómo haría esto?

+0

posible duplicado de [¿cómo puedo cambiar parte de color de una TextView?] (Http://stackoverflow.com/questions/4032676/ how-can-i-change-color-part-of-a-textview) –

+0

Si hay un texto largo en TextView, hay [una forma más eficiente] (http://stackoverflow.com/a/34449956/ 3414180) – Mingfei

+0

Posible duplicado de [Set color del lapso de TextView en Android] (http://stackoverflow.com/questions/3282940/set-color-of-textview-span-in-android) – Suragch

Respuesta

177

Usar spans.

Ejemplo:

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

Realmente no me gusta la solución que ofrece Android aquí, ya que no funciona con varios idiomas ya que no tengo idea de cuántos caracteres de mis palabras son. Actualmente estoy buscando una solución en la que pueda tener múltiples tramos que pueda adjuntar a un TextView y luego se juntan – philipp

+1

El comentario que dice span para hacer que el texto sea negrita, ¿debe decir span para hacer el color del texto? – Ryan

+8

@philipp si su problema es cuántos caracteres hay en su palabra, use el método length() en su String o StringBuilder o cualquiera que sea –

4

Si desea utilizar HTML, es necesario utilizar TextView.setText(Html.fromHtml(String htmlString))

Si usted quiere hacer que a menudo/varias veces, es posible echar un vistazo a una clase (SpannableBuilder) escribí, como Html.fromHtml() no es muy eficiente (está usando una gran maquinaria de análisis xml dentro). Se describe en este blog posting.

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

Esta es una solución mucho mejor al problema original que la respuesta marcada es . – BSnapZ

+1

Si tiene saltos de línea \ n, esto no muestra los saltos de línea. –

+6

No, no es más bonito, no hay ninguna característica para colorear, mencionado en cuestión, pero el método LENTO de HTML() –

7

Puede utilizar un Spannable para dar ciertas partes de un texto ciertos aspectos. Puedo buscar un ejemplo si quieres.

Ah, desde aquí en 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

espero que esto le ayuda (funciona con idiomas múltiples).

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

Y en su código de Java, que puede hacer:

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

De esta manera, sólo se puede colorear la parte de "Prueba" (y negrita).

+3

Best Answer. Esto funciona perfectamente para cadenas internacionalizadas. También tiene la ventaja de poder tener su texto coloreado en el medio de su recurso de cadena. –

+0

Para obtener más explicaciones, consulte la sección ** Estilo con marcado HTML ** [aquí] (http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling). – Elisa

16

He aquí un ejemplo que buscará todas las apariciones de una palabra (mayúsculas y minúsculas), y el color de rojo:

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

me encanta tu nombre: P ¿Puedo cambiar el fondo de una palabra específica con el nuevo BackgroundColorSpan (Color.parseColor ("# BFFFC6"))? –

1

Puede concatenar dos o más tramos. De esta forma es más fácil colorear texto dinámico utilizando el valor de longitud.

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

utilizar el código de su útil

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 utilizar este código:

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

Usando

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

textView.setText(spannable); 

enter image description here

Cuestiones relacionadas