我有一个带有单选列表和两个按钮的警报对话框:一个 OK
按钮和一个 cancel
按钮。下面的代码展示了我是如何实现它的。
private final Dialog createListFile(final String[] fileList) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Compare with:");
builder.setSingleChoiceItems(fileList, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.d(TAG,"The wrong button was tapped: " + fileList[whichButton]);
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
});
return builder.create();
}
我的目标是在点击 OK
按钮时获取所选单选按钮的名称。我试图将字符串保存在变量中,但在内部类中只能访问最终变量。有没有办法避免使用最终变量来存储选定的单选按钮?
最佳答案
使用 final 变量显然是行不通的(因为它只能在声明时分配一次)。所谓的“全局”变量通常是一种代码味道(尤其是当它们成为 Activity 类的一部分时,通常是创建 AlertDialogs 的地方)。 更简洁的解决方案是将 DialogInterface 对象转换为 AlertDialog,然后调用 getListView().getCheckedItemPosition()。像这样:
new AlertDialog.Builder(this)
.setSingleChoiceItems(items, 0, null)
.setPositiveButton(R.string.ok_button_label, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
// Do something useful withe the position of the selected radio button
}
})
.show();
关于android - 如何使用单选复选框android在AlertDialog中选择一个条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5660887/