Est-il possible de changer la couleur du texte d'une chaîne en plusieurs couleurs en Java?

StackOverflow https://stackoverflow.com/questions/8405661

Question

Ce que je veux dire, c'est qu'il est possible de changer le texte "Ce texte est bleu" en bleu en une seule chaîne?Il doit y avoir un moyen ...

<TextView
    android:gravity="left"
    android:padding="3dip"
    android:text="This text is white. This text is blue."
    android:textColor="#ffffff"
    android:textSize="22dp"/>
Était-ce utile?

La solution

Oui, c'est possible.Pour cela, vous devez utiliser SpannableString et ForegroundColorSpan .

Cela devrait ressembler à ceci:

SpannableStringBuilder builder = new SpannableStringBuilder();

String red = "this is red";
SpannableString redSpannable= new SpannableString(red);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
builder.append(redSpannable);

String white = "this is white";
SpannableString whiteSpannable= new SpannableString(white);
whiteSpannable.setSpan(new ForegroundColorSpan(Color.WHITE), 0, white.length(), 0);
builder.append(whiteSpannable);

String blue = "this is blue";
SpannableString blueSpannable = new SpannableString(blue);
blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blue.length(), 0);
builder.append(blueSpannable);

mTextView.setText(builder, BufferType.SPANNABLE);

entrez la description de l'image ici

Autres conseils

Un moyen simple de le faire est d'utiliser du HTML et de définir le texte sur le TextView par programmation.

String text = "This text is white. <font color=\"blue\">This text is blue.</font>";
textView.setText(Html.fromHtml(text), BufferType.SPANNABLE);

Essayez ceci ..

TextView update= (TextView) dialog.findViewById(R.id.address);
String colorText= "Driver is nearby "
                + "<font color=\"#E72A02\"><bold>"
                + "43, KR Rd, Tata Silk Farm, Jayanagar"
                + "</bold></font>"
                + " and he is "
                + "<font color=\"#B92000\"><bold>"
                + "11 km"
                + "</bold></font>"
                + " & "
                + "<font color=\"#B92000\"><bold>"
                + "20 mins"
                + "</bold></font>"
                + " away from your current location.";

        update.setText(Html.fromHtml(colorText));

et le résultat sera comme ceci.

result

Html.fromHtml(String) est obsolète dans Android N

Pour prendre en charge la dernière version d'Android donc quelque chose comme ça

 val colorText = ("Some Normal Text\n" 
                    + "<font color=\"#FFA500\"><bold> Orange Text </bold></font>"
                    + "More Normal text")

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            venueAddressValue.setText(Html.fromHtml(colorText, Html.FROM_HTML_MODE_LEGACY));
        } else {
            venueAddressValue.setText(Html.fromHtml(colorText));
        }

J'ai créé une classe comme celle-ci:

import android.text.SpannableStringBuilder;
import android.text.style.CharacterStyle;

public class StyleableSpannableStringBuilder extends SpannableStringBuilder {
    public StyleableSpannableStringBuilder appendWithStyle(CharacterStyle c, CharSequence text) {
        super.append(text);
        int startPos = length() - text.length();
        setSpan(c, startPos, length(), 0);
        return this;
    }

    public StyleableSpannableStringBuilder appendWithStyle(CharacterStyle [] c, CharSequence text) {
        super.append(text);
        int startPos = length() - text.length();
        for (CharacterStyle c1 : c)
            setSpan(c1, startPos, length(), 0);         
        return this;
    }       
}

Cela me permet de faire des choses comme celle-ci:

private void buildTickerItem(DelayedQuoteServiceObject o)
{   
    Double lastPrice = Double.parseDouble(o.getValue("LastPrice"));
    Double dayChange = Double.parseDouble(o.getValue("DayChange"));
    Double percentChange = Double.parseDouble(o.getValue("PercentDayChange")) / 100;

    if (o.isIndex() == true)
    {

        tickerTapeData.appendWithStyle(new StyleSpan(Typeface.BOLD),o.getDisplayName());            
        tickerTapeData.append(" "+ indexFormat.format(lastPrice) + " (");

        if (dayChange >= 0)
            tickerTapeData.appendWithStyle(new ForegroundColorSpan(Colours.getTickerPositive()), indexFormat.format(dayChange));        
        else
            tickerTapeData.appendWithStyle(new ForegroundColorSpan(Color.RED), indexFormat.format(dayChange));
    }
    else
    {
        tickerTapeData.appendWithStyle(new StyleSpan(Typeface.BOLD), o.ticker);

        tickerTapeData.append("@"+ dollarFormat.format(lastPrice) + " (");              

        if (dayChange >= 0)
            tickerTapeData.appendWithStyle(new ForegroundColorSpan(Colours.getTickerPositive()), dollarFormat.format(dayChange));       
        else
            tickerTapeData.appendWithStyle(new ForegroundColorSpan(Color.RED), dollarFormat.format(dayChange));


    }

    tickerTapeData.append("/");


    if (dayChange >= 0)
        tickerTapeData.appendWithStyle(new ForegroundColorSpan(Colours.getTickerPositive()), percentFormat.format(percentChange));      
    else
        tickerTapeData.appendWithStyle(new ForegroundColorSpan(Color.RED), percentFormat.format(percentChange));

    tickerTapeData.append(")  ");       
}

Pour créer une bande magnétique.Fonctionne très bien et garde le code propre.

Vous pouvez essayer ceci: Dans un fragment:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

View rootView = inflater.inflate(
                R.layout.shipment_accepted_fragment,
                container, false);

        String email = "(abc@gmail.com)";

        TextView shipment_email = (TextView) rootView
                .findViewById(R.id.textview);
        String text_shipment_email = "Hello"
                + " <font color='"
                + getResources().getColor(R.color.green_color) + "'>" + email
                + "</font>"
                + "Bye";
        shipment_email.setText(Html.fromHtml(text_shipment_email),
                TextView.BufferType.SPANNABLE);
}

Je suis utilisé pour une étoile de changement si le service "Onward"

String c = "*" + getResources().getString(R.string.rupee) + str_pay_at_store;
SpannableString spannable2 = new SpannableString(c);
spannable2.setSpan(new ForegroundColorSpan(Color.RED), 0, 1, 
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv_payatstore.setText(spannable2);

Vous pouvez voir comme ça

 entrez la description de l'image ici

String text = "<font color=#000>this color is black </font><font color=#6ab04c>this color is green</font>";

textview.setText(Html.fromHtml(text));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top