Trey Balut
Trey Balut

Reputation: 1395

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"
   />

Upvotes: 4

Views: 14370

Answers (3)

user
user

Reputation: 87064

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));

Upvotes: 9

jyotiprakash
jyotiprakash

Reputation: 2086

use android:textColor="hex code" parameter inside the TextView tag

Upvotes: 4

Nikunj Patel
Nikunj Patel

Reputation: 22066

You can change through xml and java code(runtime) also....

in xml widget you need to define ::

 android:textColor="Hex code"

Like ::

android:textColor="#000000"

at runtime you need to define ::

 TextView tv = (TextView) aView.findViewById(R.id.txvx);
                tv.setTextColor(Color.RED);

Upvotes: 3

Related Questions