通过适配器更改listview中行的背景颜色

时间:2013-06-13 02:25:29

标签: android android-listview

我正在尝试实现类似选择行为的gmail:当我点击某个项目时,它会被选中或取消选择,并在所选项目上绘制自定义颜色。我使用this作为参考。

出于某种原因,它只在我选择/取消选择一些项目后才有效。之后,调用getView(),一切都按预期工作。 为什么不从头开始调用getView()?

ListActivity:

@Override
public void onListItemClick(ListView parent, View view, int position, long id) {
    super.onListItemClick(parent, view, position, id);
    mSimpleCursorAdapter.toggleSelected(new Integer(position));
}

适配器:

 public ArrayList<Integer> selectedIds = new ArrayList<Integer>();

@Override
 public View getView(int position, View convertView, ViewGroup parent) {
    mCursor = (Cursor) getItem(position);
    ViewHolder holder = null;
    int col = -1;

    if(convertView == null) 
    {   
        holder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.row, parent, false);

        holder.mTitle = (TextView) convertView.findViewById(R.id.titleID);
        convertView.setTag(holder);

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

    col = mCursor.getColumnIndex(ReminderColumns.TITLE);
    holder.mTitle.setText(mCursor.getString(col));

    if (selectedIds.contains(position)) {
        convertView.setSelected(true);
        convertView.setPressed(true);
        convertView.setBackgroundColor(mContext.getResources().getColor(R.color.orange));
    }
    else
    {
        convertView.setSelected(false);
        convertView.setPressed(false);
        convertView.setBackgroundColor(mContext.getResources().getColor(R.color.white));
    }   
return convertView; 
}

public void toggleSelected(Integer position)
{
    if(selectedIds.contains(position))
    {
        selectedIds.remove(position);
    }
    else
    {
        selectedIds.add(position);
    }
}

1 个答案:

答案 0 :(得分:1)

您是否尝试过添加notifyDataSetChanged()

也许像这样添加它会有所帮助:

@Override
public void onListItemClick(ListView parent, View view, int position, long id) {
    super.onListItemClick(parent, view, position, id);
    mSimpleCursorAdapter.toggleSelected(new Integer(position));
    mSimpleCursorAdapter.notifyDataSetChanged();
}