我正在尝试实现类似 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);
}
}