无法从ListView中获取实际检查的项目
我在获取ListView上的检查项目时遇到问题。 事情是,无论什么时候我调用getCheckedItemsCount()或getCheckedItemPositions()它总是返回1.无论是否有0或2或更多的项目检查。无法从ListView中获取实际检查的项目
这是我的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它不......任何线索?
的问题是,ListView控件实例是越来越全乱了这样而不是使用项目列表视图的检查值的,我用了CheckBox控件的ckeched值。
这一变化是在ListAdapter做出的复选框的onCheckedChanged方法:
以前的代码:
listView.setItemChecked(position, !isChecked);
新代码:
listView.setItemChecked(position, pCompound.isChecked());
我相信你在基础适配器中缺少一些覆盖。我认为你需要实现这样的事情:(除了getView)
@Override
public int getCount() {
return myarray.size();
}
@Override
public Object getItem(int position) {
return myarray.get(position);
}
@Override
public long getItemId(int position) {
return myarray.get(position).getId();
}
我发现了这个问题,但是这带来了一个新问题。请看看编辑过的帖子。 我已经实现了这些覆盖,但我只是放置了相关的代码,因为问题不在适配器本身。 – 2013-03-21 18:34:16
什么排布置您使用的?它不看它实现可检查... – Sam 2013-03-21 17:17:30
@Sam我发现了问题,但这带来了一个新问题。请看看编辑过的帖子。我正在使用包含复选框的自定义布局。 – 2013-03-21 18:33:58