问题
So I've managed to create a context menu bar and it selects the colour of an item based on if it is checked or not.
It works fine for only 2 problems:
When the items are checked...further down in the list other items become checked as well, when they were never even selected (I am assuming it has to do with listview recycling on the getChildPosition)?
Also when my context menu bar closes...the highlighting stays and am not really sure how to remove it?
The solution: Remove the highlighting when the context menu bar closes and only highlight what I select to highlight.
Any ideas?
My Class:
listview = (ListView) findViewById(R.id.lst_contacts);
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listview.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
try
{
final int checkedCount = listview.getCheckedItemCount();
mode.setTitle("Contacts: " + checkedCount);
if (checked)
{
count = count+1;
listview.getChildAt(position).setBackgroundColor(Color.parseColor("#6DCAEC"));
}
else
{
count = checkedCount;
listview.getChildAt(position).setBackgroundColor(Color.parseColor("#E7E8E9"));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contact_context_menu, 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.delete_id:
Toast.makeText(getBaseContext(), count + " Contacts Deselected", Toast.LENGTH_SHORT).show();
count = 0;
mode.finish();
case R.id.save_id:
Toast.makeText(getBaseContext(), count + " Contacts Saved", Toast.LENGTH_SHORT).show();
count = 0;
mode.finish();
case R.id.load_id:
Toast.makeText(getBaseContext(), count + " Contacts Loaded", Toast.LENGTH_SHORT).show();
count = 0;
mode.finish();
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
});
来源:https://stackoverflow.com/questions/29021329/context-menu-selecting-color-with-listview-recycling