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());
}
}
});
这是我的代码,用于在警报对话框中制作一个带有复选框的列表。它可以有多个选择。我的问题是我可以获得默认选中复选框的值。只有当用户手动选中该复选框时,我才能获取该值。
如果默认选中,如何获取复选框的值。
更新
ListView lv = ((AlertDialog) dialog).getListView();
System.out.println("asd" + "pos = " + lv.getCheckedItemPosition());
System.out.println("asd" + "which = " + which);
我用过这个但是点击确定按钮但是我在位置上得到-1而在哪个位置上得到-1
最佳答案
在带有列表项的 AlertDialog
中,您可以使用 getListView()
方法获取默认的 ListView
。
在具有多项选择模式的 ListView
中,getCheckedItemPositions()
将返回一个包含选中项的 SparseBooleanArray
。
将它们放在一起,您可以获得所有选定的项目,包括那些在展示时选中的项目。
关于java - 如何在警报对话框android java中获取默认选中复选框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40279724/