我在获取列表视图中的已检查项目时遇到问题。问题是,无论我何时调用 getCheckedItemsCount() 或 getCheckedItemPositions(),它总是返回 1。无论检查了 0 个或 2 个或更多项目。
这是我的 MainActivity,它实现了 MultiChoiceModeListener,用于在检查项目时进行监听。我这样做是因为我在 ListAdapter 上动态检查项目。
public class MainActivity extends ListActivity implements MultiChoiceModeListener
{
@Override
protected void onCreate (Bundle bundle)
{
super.onCreate (bundle);
// Set our view from the "main" layout resource
setContentView (R.layout.main);
this.getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
this.getListView().setMultiChoiceModeListener(this);
_dataAdapter = new ServerListAdapter (this);
this.getListView(). setAdapter(_dataAdapter);
registerForContextMenu (this.getListView());
}
// This is called when i set the item as checked using setItemChecked on my ListAdapter.
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean isChecked) {
SparseBooleanArray checke = getListView().getCheckedItemPositions();
// This always returns 1. No matter If I have 0 or 2 items checked.
int checkedCount = checkedItemPositions.size();
// I Have also tried with getCheckedItemsCount() and it returns 1 too.
if (checkedCount > 0)
{
// DO SOMETHING...
}
else
{
// DO SOME OTHER STUFF...
}
}
这是我的 ListAdapter 的代码。这里只有相关代码:
public class ServerListAdapter extends BaseAdapter {
@Override
public View getView (final int position, final View convertView, final ViewGroup parent)
{
final ListView listView = (ListView)parent;
boolean isChecked = listView.isItemChecked(position);
((CheckBox)view.findViewById(R.id.chkItemServerSelected)).setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton pCompound, boolean arg1)
{
boolean isChecked = listView.isItemChecked(position);
// Here i set the item as checked, o unchecked. This works ok.
listView.setItemChecked(position, !isChecked);
}
});
//Finally return the view
return view;
}
}
编辑:
环顾四周后,我发现问题在于我做错了。
在我的列表适配器上,在 onCheckedChanged 上,我必须使用复选框中的值,而不是使用从列表视图中获取的当前值(因为这是我想要实现的)。
以前的代码:
listView.setItemChecked(position, !isChecked);
新代码:
listView.setItemChecked(position, pCompound.isChecked());
问题是这带来了一个新问题。当检查值 IsChecked 为TRUE时,会引发事件 onItemCheckedStateChanged,但当值为FALSE时,它不会......任何线索?