【发布时间】:2015-11-16 20:44:28
【问题描述】:
我有以下代码:
final AlertDialog.Builder builder = new AlertDialog.Builder(Activity.this);
builder.setTitle(R.string.str_dbox_remove_plant_title);
final HashMap<String, Integer> stuff = myCollection.getListOfStuffWithLocation();
final CharSequence[] items = stuff.keySet().toArray(new CharSequence[stuff.size()]);
final List<Integer> indexesOfSelectedStuff = new ArrayList<Integer>();
builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked)
indexesOfSelectedStuff.add(stuff.get(items[which].toString()));
else if (indexesOfSelectedStuff.contains(stuff.get(items[which].toString())))
indexesOfSelectedStuff.remove(which);
}
});
builder.setPositiveButton(R.string.str_dbox_remove_stuff_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
for (int i = 0; i < indexesOfSelectedStuff.size(); i++) {
myCollection.removeStuff(i);
}
}
});
builder.setNegativeButton(R.string.str_dbox_remove_stuff_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setCancelable(false); // so as to prevent the back button from closing the dialog box
final AlertDialog alert = builder.create();
alert.setCanceledOnTouchOutside(false);
alert.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false); // by default, disable OK button
alert.show();
我有一个AlertDialog 和一些CheckBoxes,我想禁用PositiveButton,只要没有选中任何CheckBoxes。
我有一个名为indexesOfSelectedStuff 的List,你可以说,在某种程度上,使用它的size() 方法可以让我知道选择了多少CheckBoxes。但是,我不确定在哪里放置它或如何在构建器中引用PositiveButton。我想把它放在onClick 方法上(在OnMultipleChoiceClickListener() 中定义),像这样:
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked)
indexesOfSelectedStuff.add(stuff.get(items[which].toString()));
else if (indexesOfSelectedStuff.contains(stuff.get(items[which].toString())))
indexesOfSelectedStuff.remove(which);
if (indexesOfSelectedStuff.size() == 0) {
// disable button
// but problem is, I don't know how to reference the POSITIVE_BUTTON
}
else {
// enable button
}
}
我知道我很可能无法将其插入那里。在创建AlertDialog 之后,我必须进行检查。但如果是这样的话,你会建议我使用什么?我在想Listeners 但是哪个?我应该怎么做?
【问题讨论】:
-
我知道它与此类似:How to disable / enable dialog negative positive buttons?。所以,那里的答案有点建议我为我所有的
CheckBoxes 做听众,但我真的不知道他们有多少。或者他们的身份证,甚至。因为我只是让AlertDialog.Builder为我做这件事。
标签: android button checkbox android-alertdialog builder