我有一个ListView,当我点击一个项目时,我希望它以一种确定的颜色着色,因为当我点击一个项目来竞争上下文操作栏时,为什么人们必须看到列表中的哪些项目是选择。我写了这段代码。
private void onListItemSelect(int position) {
adapter.toggleSelection(position);
boolean hasCheckedItems = adapter.getSelectedCount() > 0;
if (hasCheckedItems && mActionMode == null)
// there are some selected items, start the actionMode
mActionMode = startSupportActionMode(new ActionModeCallback());
else if (!hasCheckedItems && mActionMode != null)
// there no selected items, finish the actionMode
mActionMode.finish();
if (mActionMode != null)
mActionMode.setTitle(String.valueOf(adapter.getSelectedCount()) + " selezionati");
}
private class ActionModeCallback implements ActionMode.Callback {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// inflate contextual menu
mode.getMenuInflater().inflate(R.menu.contextual_action_bar, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item1:
item.setIcon(R.drawable.delete_pressed);
//mode.finish();
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// remove selection
adapter.removeSelection();
mActionMode = null;
}
}
applicationListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
adapter.isSelected(true, view);
onListItemSelect(position);
}
});
在我的适配器中我
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public int getSelectedCount() {
return mSelectedItemsIds.size();
}
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void isChecked(boolean checked, View v) {
if(checked) {
v.setBackgroundColor(Color.LTGRAY);
}
else {
v.setBackgroundColor(Color.TRANSPARENT);
}
}
问题在于,当我点击该项目时,正确地着色并出现上下文操作栏,到目前为止一切都很顺利。问题是即使不再有上下文操作栏,元素仍然是彩色的。我希望当它恢复到正常颜色时,然后清除。我该怎么办?