リストビューでチェック済みアイテムを取得する際に問題が発生しています。問題は、getCheckedItemsCount() または getCheckedItemPositions() を呼び出すと、常に 1 が返されるということです。0 または 2 つ以上のアイテムがチェックされているかどうかに関係なく。
これは、MultiChoiceModeListener を実装する MainActivity で、項目がチェックされたときにリッスンします。これを行うのは、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の場合は発生しません...手がかりはありますか?