androidtextviewspannablestringspannablespannablestringbuilder

change string color programmatically depending if condition


Is it possible to set multiple colors for different pieces of text inside a TextView with if condition?

Here is my code:

mColoredText = findViewById(R.id.questionText);
        String mColoredString = "BLACK RED GREEN YELLOW ORANGE BLUE WHITE";
        SpannableStringBuilder builder = new SpannableStringBuilder();

        if(mColoredString.contains("RED")) {
            String red = "RED";
            SpannableString redSpannable = new SpannableString(red);
            redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0);
            builder.append(redSpannable);
        }

        if(mColoredString.contains("YELLOW")) {
            String yellow = "YELLOW";
            SpannableString whiteSpannable = new SpannableString(yellow);
            whiteSpannable.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, yellow.length(), 0);
            builder.append(whiteSpannable);
        }

        if(mColoredString.contains("BLUE")) {
            String blue = "BLUE";
            SpannableString blueSpannable = new SpannableString(blue);
            blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blue.length(), 0);
            builder.append(blueSpannable);
        }

        mColoredText.setText(builder, TextView.BufferType.SPANNABLE);

But the end result is always print: RED YELLOW BLUE with it's color, just three text.

I expect BLACK RED GREEN YELLOW ORANGE BLUE WHITE written all together, and white color applicable if no spannable color.


Solution

  • Try this code..

        textView = findViewById(R.id.tvData);
        String mColoredString = "BLACK RED GREEN YELLOW ORANGE BLUE WHITE";
        SpannableStringBuilder builder = new SpannableStringBuilder();
    
        String strArray[] = mColoredString.split(" ");
        for (int i = 0; i < strArray.length; i++) {
            if (strArray[i].equals("RED")) {
                SpannableString redSpannable = new SpannableString(strArray[i]);
                redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, strArray[i].length(), 0);
                builder.append(redSpannable);
            } else if (strArray[i].equals("YELLOW")) {
                SpannableString whiteSpannable = new SpannableString(strArray[i]);
                whiteSpannable.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, strArray[i].length(), 0);
                builder.append(whiteSpannable);
            } else if (strArray[i].equals("BLUE")) {
                SpannableString blueSpannable = new SpannableString(strArray[i]);
                blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, strArray[i].length(), 0);
                builder.append(blueSpannable);
            } else {
                builder.append(strArray[i]);
            }
    
        }
        textView.setText(builder);
    
    }