如何更改listview特定项目的颜色?

时间:2014-05-20 09:09:52

标签: android listview android-listview android-arrayadapter

我有一个customlistadapter如下:

public class CustomListViewAdapter2 extends ArrayAdapter<RowItem> {
    List<Integer> baseOnThis;
    public CustomListViewAdapter2(Context context, int resourceId,
        List<RowItem> items, ArrayList<Integer> ids) {
    super(context, resourceId, items);
    this.context = context;
    baseOnThis= ids;
}

/* private view holder class */
private class ViewHolder {
    TextView firstHemistich;
    TextView SecondHemistich;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    RowItem rowItem = getItem(position);


    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {

        convertView = mInflater.inflate(R.layout.hemistich_rows, null);
        holder = new ViewHolder();
                    holder.firstHemistich = (TextView) convertView
                .findViewById(R.id.title);
        holder.SecondHemistich = (TextView) convertView
                .findViewById(R.id.desc);

        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();

    holder.firstHemistich.setText(rowItem.getTitle());
    holder.SecondHemistich.setText(rowItem.getDesc());

    return convertView;
}

现在我需要根据保存在“baseOnThis”的Arraylist上的数据库值来改变listview项目的颜色,但我不能。有什么想法我应该怎么做? 如果我的问题是错误的,请告诉我,不要拒绝我

3 个答案:

答案 0 :(得分:2)

试试这个

if(position == 3){
        holder.SecondHemistich.setTextColor(this.context.getResources().getColor(R.color.color1));
}   

答案 1 :(得分:0)

也许更好的方法是阅读一下有关Android Adapters Reference

的内容

Basicaly getView方法的工作方式类似于用于 foreach ,并为您可以根据需要修改的数组或列表中的每个项目返回View对象,您只需要制作getView()方法中的任何必要更改

关于更改颜色,您可以从已经膨胀的convertView获取主要布局容器,并根据需要更改其背景颜色属性

答案 2 :(得分:0)

将您的getView - 方法更改为:

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    RowItem rowItem = getItem(position);


    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {

        convertView = mInflater.inflate(R.layout.hemistich_rows, null);
        holder = new ViewHolder();
                    holder.firstHemistich = (TextView) convertView
                .findViewById(R.id.title);
        holder.SecondHemistich = (TextView) convertView
                .findViewById(R.id.desc);

        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();

    holder.firstHemistich.setText(rowItem.getTitle());
    holder.SecondHemistich.setText(rowItem.getDesc());

    // change color of item
    if (yourValueHere) {
        holder.SecondHemistich.setTextColor(yourColor);
    }

    return convertView;
}

更改yourValueHere和yourColor ...这将根据值yourValueHere为每个项目着色。