Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text color for ListView items

How do I change the text color for the items that are added to a ListView. I need to change the colors programmatically in code based on certain conditions and changing different rows to different text colors(e.g. row 0 = red, row1= white, row3= blue etc). Setting a text color in the xml layout will not meet my requirements. Here is my code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview);

    setListAdapter(new ArrayAdapter<String>(ListViewEx.this,
            R.layout.list_item_1, Global.availableDecks));

//something like this 
//listview.getPosition(0).setTextColor(red);
//listview.getPosition(1).setTextColor(white);
//listview.getPosition(2).setTextColor(blue);

and my xml:

    <?xml version="1.0" encoding="utf-8"?>


    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/label"
    android:layout_width="match_parent"
    android:layout_height="35dp"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="30px"
    android:layout_marginLeft="5px"
    android:singleLine="true"
   />
like image 561
Trey Balut Avatar asked Dec 05 '22 17:12

Trey Balut


1 Answers

Implement your own ArrayAdapter and override the getView() method:

    public class Adapter1 extends ArrayAdapter<String> {

    public Adapter1(Context context, int resID, ArrayList<String> items) {
        super(context, resID, items);                       
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);
        if (position == 1) {
            ((TextView) v).setTextColor(Color.GREEN); 
        }
        return v;
    }

}

Don't forget to provide an alternative else clause to set the color to the default so you don't have problems when you're dealing with a recycled row. Then in your activity:

setListAdapter(new Adapter1(ListViewEx.this,
            R.layout.list_item_1, Global.availableDecks));
like image 109
user Avatar answered Dec 24 '22 04:12

user