Search code examples
javaandroidandroid-arrayadapter

setting textview color in custom arrayadapter


I'm trying to set color of TextView in custom arrayadapter, but it does'nt work - I'm getting grey color text instead of green.

I tried to set default textview color in row.xml, but it did'nt had any effect either.

public class ReadCustomAdapter extends ArrayAdapter<ReadModel>{

    public ReadCustomAdapter(Activity a, int textViewResourceId, ArrayList<ReadModel> entries) {
        super(a, textViewResourceId, entries);
        this.entries = entries;
        this.activity = a;
    }

    public static class ViewHolder{
        public TextView item1;
        public TextView item2;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        ViewHolder holder;
        if (v == null) {
            LayoutInflater vi =
                (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
            holder = new ViewHolder();
            holder.item1 = (TextView) v.findViewById(android.R.id.text1);
            holder.item2 = (TextView) v.findViewById(android.R.id.text2);             
            v.setTag(holder);
        }
        else
            holder=(ViewHolder)v.getTag();

        final ReadModel custom = entries.get(position);

        if (custom != null) {
            holder.item1.setText(custom.getNick());
            holder.item2.setText(custom.getMsg());

            holder.item1.setTextColor(R.color.green);

        }
        return v;
    }

}

color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="green">#00ff00</color>
</resources>

Solution

  • The setTextColor() is expecting a color-integer (0xFF00FF00 in your case), but you supply it with the resource id of that color, which can be any number.
    You can either use it like this:

    holder.item1.setTextColor(0xFF00FF00);
    

    or like this:

    holder.item1.setTextColor(getResources().getColor(R.color.green));