Search code examples
androidlistviewandroid-arrayadaptertextcolor

Change textcolor programmatically in listview who depends of arrayadapter


I have the next estructure:

ArrayList<String> arrayList = new ArrayList<>();
list = (ListView) findViewById(R.id.list1);

arrayAdapter = new ArrayAdapter<String>(INGR_NOTAS.this, R.layout.list_item_clickable, R.id.txtitem, arrayList);

list.setAdapter(arrayAdapter);

where the layout of the listview comes from list_item_clickable.xml and the textiview "txtitem" inside it:

<?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">
    <TextView
        android:text="TextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtitem"
        android:textColor="@android:color/white"
        android:background="@android:drawable/editbox_dropdown_dark_frame"
        android:textAlignment="center" />
</LinearLayout>

This estructure is working in a lot of classes and like Textview says, the textcolor is always white, but now I need to change the textcolor inside of the listview depending of the value of the text (sometimes white, sometimes red). So, How can I add this change without add a big impact in the rest of the code a long all the App????

Thanks for any advice!!


Solution

  • try this:

    ArrayList<String> arrayList = new ArrayList<>();
    list = (ListView) findViewById(R.id.list1);
    
    arrayAdapter = new ArrayAdapter<String>(INGR_NOTAS.this, R.layout.list_item_clickable, R.id.txtitem, arrayList){
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            View view = super.getView(position, convertView, parent);
            ((TextView)view.findViewById(R.id.txtitem)).setTextColor(position % 2 == 0 ? Color.WHITE : Color.RED); // here can be your logic
            return view;
        };
    };
    
    list.setAdapter(arrayAdapter);
    

    hope it helps