【发布时间】:2017-03-09 20:23:20
【问题描述】:
final List < CharSequence > checkedsurveylist = new ArrayList < CharSequence > ();
final JSONArray jsonArray = new JSONArray(response);
final boolean[] checkedItems = new boolean[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = (JSONObject) jsonArray.get(i);
String syncstatus = "";
if (obj.get("syncstatus").toString().matches("1")) {
syncstatus = "Not yet synchronized";
checkedItems[i] = false;
} else if (obj.get("syncstatus").toString().matches("2")) {
syncstatus = "Synchronized";
checkedItems[i] = true;
}
checkedsurveylist.add("(" + obj.get("sysid").toString() + ")" + obj.get("surveytitle").toString() + " - " + syncstatus);
}
System.out.println("checkedItems " + checkedItems);
final List < String > mSelectedItems = new ArrayList < String > ();
final List < Integer > mSelectedItemsindex = new ArrayList < Integer > ();
AlertDialog.Builder builder = new AlertDialog.Builder(Connect_server.this);
builder.setTitle("Survey List")
.setMultiChoiceItems(checkedsurveylist.toArray(new CharSequence[checkedsurveylist.size()]), checkedItems,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
checkedsurveylist.toArray()[which] = isChecked;
// Get the current focused item
String currentItem = checkedsurveylist.get(which).toString();
// Notify the current action
Toast.makeText(getApplicationContext(),
currentItem + " " + isChecked, Toast.LENGTH_SHORT).show();
if (isChecked) {
mSelectedItems.add(checkedsurveylist.get(which).toString());
mSelectedItemsindex.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItemsindex.remove(Integer.valueOf(which));
mSelectedItems.remove(Integer
.valueOf(which));
}
}
});
// Set the positive/yes button click listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do something when click positive button
System.out.println("asdasdasd " + mSelectedItemsindex.size());
for (int i = 0; i < mSelectedItemsindex.size(); i++) {
System.out.println("asdasdasd " + checkedsurveylist.get(i).toString());
}
}
});
这是我在警报对话框中制作带有复选框的列表的代码。它可以有多个选择。我的问题是我可以获得默认选中复选框的值。如果复选框由用户手动检查,我只能获取该值。
如果默认选中,如何获取复选框的值。
Update
ListView lv = ((AlertDialog) dialog).getListView();
System.out.println("asd" + "pos = " + lv.getCheckedItemPosition());
System.out.println("asd" + "which = " + which);
我使用了这个,但是点击 OK 按钮,但我在位置上得到 -1,在哪个位置上得到 -1
【问题讨论】:
-
在 CheckBox 的实例上调用
isChecked()? -
你能告诉@Blackbelt在哪里以及如何
-
为什么不在
for循环中将预先检查的项目添加到您的ArrayLists 中?如果您不想这样做,AlertDialog#getListView().getCheckedItemPositions()将返回带有选中位置的SparseBooleanArray。 -
再看一遍。
getCheckedItemPositions(),复数。 -
@MikeM。它起作用了我用这个
ListView lv = ((AlertDialog) dialog).getListView(); SparseBooleanArray checkedItems = lv.getCheckedItemPositions();你能把它作为答案发布,这样我就可以关闭这个OP
标签: java android checkbox android-alertdialog