2010-07-19 21 views

Respuesta

313

Otra respuesta sería muy similar, pero no habría necesidad de establecer el texto de la TextView dos veces

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

, pero ¿cómo puedo cambiar el color de varias palabras? ¿Todos los textos no abarcan un lapso? –

+0

@mostafahashim crear múltiples tramos repitiendo la línea 3 wordtoSpan.setSpan (nuevo ForegroundColorSpan (Color.RED), 50, 80, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); –

16

configurar un texto de TextView spannable y definir un ForegroundColorSpan para el texto.

TextView textView = (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);  
textView.setText(wordtoSpan); 
+0

Gracias! ¿Es posible hacer esto sin asignar el texto primero a TextView? – hpique

+0

No me expliqué bien.Déjame reformular. ¿Las primeras 3 líneas son necesarias? ¿No puedes crear el objeto Spannable desde la cadena directamente? – hpique

+0

Nop, debe almacenar el texto de su TextView en un Buffer Spannable para cambiar el color de primer plano. – Jorgesys

71

Aquí es un poco de función de ayuda. ¡Ideal para cuando tienes múltiples idiomas!

private void setColor(TextView view, String fulltext, String subtext, int color) { 
    view.setText(fulltext, TextView.BufferType.SPANNABLE); 
    Spannable str = (Spannable) view.getText(); 
    int i = fulltext.indexOf(subtext); 
    str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
} 
+0

no, puedes hacer lo que quieras con HTML. –

5

Hay una fábrica para crear el Spannable, y evitar el reparto, así:

Spannable span = Spannable.Factory.getInstance().newSpannable("text"); 
+1

¿Podría aclarar cómo usar SpannableFactory? ¿Cómo debería verse el "texto"? – Piotr

+0

después de crear el Spannable por SpannableFactory, entonces, ¿cómo usarlo? – MBH

12

Otra forma en que podría ser utilizado en algunas situaciones es establecer el color de los enlaces en las propiedades de la vista que está tomando el Spannable.

Si su Spannable va a ser utilizado en un TextView, por ejemplo, puede definir el color de los enlaces en el XML de la siguiente manera:

<TextView 
    android:id="@+id/myTextView" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:textColorLink="@color/your_color" 
</TextView> 

También puede establecer en el código con:

TextView tv = (TextView) findViewById(R.id.myTextView); 
tv.setLinkTextColor(your_color); 
23

Si desea más control, es posible que desee comprobar la clase TextPaint.Aquí es cómo usarlo:

final ClickableSpan clickableSpan = new ClickableSpan() { 
    @Override 
    public void onClick(final View textView) { 
     //Your onClick code here 
    } 

    @Override 
    public void updateDrawState(final TextPaint textPaint) { 
     textPaint.setColor(yourContext.getResources().getColor(R.color.orange)); 
     textPaint.setUnderlineText(true); 
    } 
}; 
+0

getColor (ID int) está en desuso en Android 6.0 Marshmallow (API 23) https://stackoverflow.com/questions/31590714/getcolorint-id-deprecated-on-android-6-0-marshmallow-api-23 –

4

Establecer color en texto por pasar Cadena y de color:

private String getColoredSpanned(String text, String color) { 
    String input = "<font color=" + color + ">" + text + "</font>"; 
    return input; 
} 

Conjunto texto en Vista de Texto/botón/EditarTexto etc. llamando al código siguiente:

TextView:

TextView txtView = (TextView)findViewById(R.id.txtView); 

Consigue color de la secuencia:

String name = getColoredSpanned("Hiren", "#800000"); 

Conjunto de texto en la Vista de Texto:

txtView.setText(Html.fromHtml(name)); 

Hecho

16

Siempre encuentro ejemplos visuales útiles cuando trato de entender un nuevo concepto.

Color de fondo

enter image description here

SpannableString spannableString = new SpannableString("Hello World!"); 
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW); 
spannableString.setSpan(backgroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
textView.setText(spannableString); 

Color de primer plano

enter image description here

SpannableString spannableString = new SpannableString("Hello World!"); 
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED); 
spannableString.setSpan(foregroundSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
textView.setText(spannableString); 

Combinación

enter image description here

SpannableString spannableString = new SpannableString("Hello World!"); 
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED); 
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW); 
spannableString.setSpan(foregroundSpan, 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
spannableString.setSpan(backgroundSpan, 3, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
textView.setText(spannableString); 

El estudio adicional

0
  1. crear TextView en ur diseño
  2. pega este código en ur MainActi vidad

    TextView textview=(TextView)findViewById(R.id.textviewid); 
    Spannable spannable=new SpannableString("Hello my name is sunil"); 
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE); 
    textview.setText(spannable); 
    //Note:- the 0,5 is the size of colour which u want to give the strring 
    //0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily 
    
0
private SpannableString spannableString(SpannableString spannableString, int start, int end) { 
    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901}); 
    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null); 

    spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

    return spannableString; 
} 

SpannableString spannableString = new SpannableString("I don't like Hasina."); 
spannableString(spannableString, 8, 14); 
textView.setText(spannableString); 

Salida:

enter image description here

Cuestiones relacionadas