编辑:好的,我找到了解决方案。不知道这是正确的解决方案,但它确实可以正常工作。添加到下面的代码中。
我正在尝试允许用户从核对清单中选择多个目录,并在单击“提交”按钮时返回它们。这是我的代码片段。它使用/ sdcard /上的所有目录填充ListView,并且当我提交时,初始选择(无论我选择多少),日志显示返回的正确选项。但是,如果我取消选中一个项目,然后再次点击“提交”,它仍会显示所有内容都被选中。我是否需要编写处理程序来取消选中项目?我认为这是由选择模式选择照顾的?谢谢!
private SparseBooleanArray a;
directoryList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, directoryArray));
submitButton = (Button)findViewById(R.id.submit_button);
submitButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
a = new SparseBooleanArray();
a.clear();
a = directoryList.getCheckedItemPositions();
for (int i = 0; i < a.size(); i++)
{
//added if statement to check for true. The SparseBooleanArray
//seems to maintain the keys for the checked items, but it sets
//the value to false. Adding a boolean check returns the correct result.
if(a.valueAt(i) == true)
Log.v("Returned ", directoryArray[a.keyAt(i)]);
}
}
});
答案 0 :(得分:4)
我知道你找到了一个适合你的解决方案,但是大多数时候可能会工作的更简洁的解决方案就是这个(我希望保留所选元素的所有ID):
(在我的ListActivity中):
SparseBooleanArray selectedPos = getListView()
.getCheckedItemPositions();
ListAdapter lAdapter = getListAdapter();
List<Long> ids = new ArrayList<Long>();
for (int i = 0; i < lAdapter.getCount(); i++) {
if (selectedPos.get(i)) {
ids.add(lAdapter.getItemId(i));
}
}
答案 1 :(得分:3)
做了一些调试并找到了适合我的解决方案。编辑成上面的代码。出于某种原因,SparseBooleanArray不会自行清空;它维护已检查的框的键。但是,当调用getCheckedItemPositions()时,它会将VALUE设置为false。所以键仍然在返回的数组中,但它的值为false。只有选中的复选框才会标记为true。
答案 2 :(得分:1)
并不是故意这样做作为答案,但我不得不扩展你做多选的做法。你为什么要为你的选择做一个字段变量?我刚刚做了本地的SparseBooleanArray ......
public class NaughtyAndNice extends ListActivity {
TextView selection;
String[] items={"lorem","ipsum", "dolor", "sit", "amet",
"consectetuer", "adipisc", "jklfe", "morbi", "vel",
"ligula", "vitae", "carcu", "aliequet"};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,items));
selection = (TextView)findViewById(R.id.selection);
this.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
public void onListItemClick(ListView parent, View view, int position, long id){
SparseBooleanArray choices = parent.getCheckedItemPositions();
StringBuilder choicesString = new StringBuilder();
for (int i = 0; i < choices.size(); i++)
{
//added if statement to check for true. The SparseBooleanArray
//seems to maintain the keys for the checked items, but it sets
//the value to false. Adding a boolean check returns the correct result.
if(choices.valueAt(i) == true)
choicesString.append(items[choices.keyAt(i)]).append(" ");
}
selection.setText(choicesString);
}
}
答案 3 :(得分:1)
无需使用SparseBooleanArray choices = parent.getCheckedItemPositions();
StringBuilder
就足够了。