2011-09-08 2 views
18

J'essaie de changer la couleur de certains mots (Résultats de la recherche) dans un TextView? J'ai essayé d'utiliser des couleurs ANSI comme ceci:Comment colorer une partie de TextView dans android?

text.setText("\u001B31;1m" + "someText"); 

mais cela n'a pas fonctionné. Comment puis-je y parvenir?

+0

Voir ceci: http://stackoverflow.com/questions/4897349/android-coloring-part-of-a-string-using-textview-settext –

Répondre

31

cela vous aidera u

Spannable WordtoSpan = new SpannableString("I know just how to whisper");   
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 5, 13, 
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
textview.setText(WordtoSpan); 
+0

5, 13 sont les charecter, s longueur. –

+4

vous voulez dire les index de début et de fin? – Marek

+0

Oui. c'est-à-dire pour quelle partie vous voulez colorier le texte. point de départ et de fin de la vue de texte colorée. –

4

Vous recherchez TextAppearanceSpan et « SpannableString » Pour être plus clair flux de travail est comme suit

  1. Créer SpannableString de votre chaîne source
  2. Créer TextAppearanceSpan et placèrent via un appel à la méthode setSpan sur SpannableString
  3. Appel méthode textView.setText avec SpannableString comme argument
2

Vous pouvez également utiliser HTML comme dans l'exemple suivant:

string = "<font color='#FFFFFF'>This is my text </font>" + "<font color='#000000'> Another text </font>"; 
textView.setText(Html.fromHtml(string)); 

Sans l'aide variable supplémentaire (solution d'une ligne):

textView.setText(Html.fromHtml("<font color='#FFFFFF'>This is my text </font>" + "<font color='#000000'> Another text </font>")); 

Il est assez facile et une solution compréhensible :)

+0

Html.fromHtml (chaîne) est maintenant obsolète. Veuillez mettre à jour votre réponse –

0

Je sais que je suis un peu en retard pour la fête mais je pense que cela va aider les futurs visiteurs. Vous pouvez définir des couleurs de texte partielles sur la mise en page XML au lieu d'utiliser du code Java, donc en fonction des réponses précédentes sur ce sujet, j'ai créé une petite classe qui fait l'affaire.

1 - Tout d'abord, nous allons créer notre composant

package yourpackagehere.component; 

import android.content.Context; 
import android.content.res.TypedArray; 
import android.graphics.Color; 
import android.text.Spannable; 
import android.text.SpannableString; 
import android.text.style.ForegroundColorSpan; 
import android.util.AttributeSet; 

import yourpackagehere.R; 

public class FontSpannableTextView extends TextView { 

    public FontSpannableTextView(Context context) { 
     super(context); 
    } 

    public FontSpannableTextView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setColorPartialString(context, attrs); 
    } 

    public FontSpannableTextView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     setColorPartialString(context, attrs); 
    } 

    private void setColorPartialString(Context context, AttributeSet attrs) { 
     if (isInEditMode()) { 
      return; 
     } 
     String partialText = null; 
     int partialTextColor = Integer.MIN_VALUE; 

     if (attrs != null) { 
      TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FontSpannableTextView); 
      for (int i = 0; i < a.getIndexCount(); i++) { 
       int attr = a.getIndex(i); 
       switch (attr) { 
        case R.styleable.FontSpannableTextView_fontspannabletextview_partialText: 
         partialText = a.getString(attr); 
         break; 
        case R.styleable.FontSpannableTextView_fontspannabletextview_partialTextColor: 
         partialTextColor = a.getColor(attr, Color.BLACK); 
         break; 
       } 
      } 
      a.recycle(); 
     } 

     if (partialText != null && partialTextColor != Integer.MIN_VALUE) { 
      String wholeText = getText().toString(); 
      Spannable spannable = new SpannableString(wholeText); 
      spannable.setSpan(new ForegroundColorSpan(partialTextColor), 
        wholeText.indexOf(partialText), 
        wholeText.indexOf(partialText) + partialText.length(), 
        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
      setText(spannable); 
     } else { 
      Log.e("YOURTAGHERE","You must provide both partialText and partialTextColor values"); 
     } 
    } 
} 

2 - sur attrs.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="FontSpannableTextView"> 
     <attr name="fontspannabletextview_partialText" format="string" /> 
     <attr name="fontspannabletextview_partialTextColor" format="color" /> 
    </declare-styleable> 
</resources> 

3 - Utilisons dans notre mise en page de test

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    xmlns:app="http://schemas.android.com/apk/res-auto"> 


    <yourpackagehere.component.FontSpannableTextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/hello_world" <!-- Hello world! --> 
     android:layout_margin="25dp" 
     app:fontspannabletextview_partialText="@string/world" <!-- world! --> 
     app:fontspannabletextview_partialTextColor="@color/tutorial_yellow" 
     android:textSize="40sp" 
     /> 

</LinearLayout> 

Exemple:

enter image description here

Questions connexes