0

I have an arraylist named incorrectAnswers, I want to change the text color of those strings inside that arraylist.

Here's a snippet of my code:

           ArrayList<String> incorrectAnswers = new ArrayList<>();
           if(mItemArray.get(0).second.startsWith("In")){
                numberOfCorrect++;
                numberOfTries++;
            } else{
                numberOfErrors++;
                incorrectAnswers.add(mItemArray.get(0).second);
            }

            if(mItemArray.get(1).second.startsWith("If")){
                numberOfCorrect++;
                numberOfTries++;
            }
            else{
                numberOfErrors++;
                incorrectAnswers.add(mItemArray.get(1).second);
            }

This is the layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item_layout"
android:layout_width="match_parent"
android:layout_height="70dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="10dp"
android:backgroundTint="@android:color/holo_green_light"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:background="@drawable/border_spinner">

<ImageView
    android:id="@+id/image"
    android:layout_width="1dp"
    android:layout_height="1dp"
    android:src="@drawable/ic_abrasion"
    android:visibility="invisible"/>

<TextView
    android:id="@+id/list_text"
    android:layout_width="wrap_content"
    android:textSize="16sp"
    android:textColor="@color/textColor"
    android:layout_height="wrap_content"/>

I want to change programmatically the text color of those items I've added inside incorrectAnswers. How can I achieve that?

Gelly
  • 127
  • 1
  • 13
  • Possible duplicate of [Set color of TextView span in Android](http://stackoverflow.com/questions/3282940/set-color-of-textview-span-in-android) – Doron Yakovlev Golani Mar 20 '17 at 18:03
  • Could you please tell me where are you using setText?And can you please give example likewise a string in which part to be coloured and which part to be left? – Janardhan R Mar 20 '17 at 18:44

1 Answers1

0

First of all create a xml in drawables folder like this to setup the color states: Lets call it text_color.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@android:color/holo_red_dark" android:state_selected="true" />
    <item android:color="@android:color/holo_green_light" />
</selector>

Then, use this xml as your text color in your layout:

<TextView
android:id="@+id/list_text"
android:layout_width="wrap_content"
android:textSize="16sp"
android:textColor="@drawable/text_color"
android:layout_height="wrap_content"/>

Finally, you have to set only the textviews that will have the incorrect answers as checked like this:

TextView textList = (TextView) findViewById(R.id.list_text);
textList.setSelected(true);
Jonathan Aste
  • 1,764
  • 1
  • 13
  • 20