0

我正在尝试实现类似 gmail 的选择行为:当我单击一个项目时,它要么被选中,要么被取消选中,并且在所选项目上绘制了自定义颜色。我用这个作为参考。

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

列表活动:

@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);
    }
}
4

1 回答 1

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();
}
于 2013-06-13T03:42:19.493 回答