【发布时间】:2016-10-19 16:40:27
【问题描述】:
我有一种方法可以从数据库中删除某些内容。我想得到用户的确认。为了做到这一点,我实现了一个布尔函数来通过对话框获得确认。
好吧,我的问题是,无论我选择是或否,我总是得到相同的错误结果。
(我使用了 final boolean[],否则会出错)
这是方法:
public boolean alertMessage() { //Confirmation to delete routine
final boolean[] confirmation = {false};
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// Yes button clicked
confirmation[0] =true;
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
// do nothing
confirmation[0]=false;
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.sure_delete)
.setPositiveButton(R.string.yes, dialogClickListener)
.setNegativeButton(R.string.no, dialogClickListener).show();
return confirmation[0];
}
这就是我在删除代码中检查它的方式:
//CONFIRMATION
if(!alertMessage()){
return;
}
更新: 用一个答案建议试试这个,但还是一样:
public boolean alertMessage() { //Confirmation to delete routine
final boolean[] confirmation = {false};
new AlertDialog.Builder(this)
.setTitle(R.string.delete)
.setMessage(R.string.sure_delete)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
confirmation[0]=true;
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
confirmation[0]=false;
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
return confirmation[0];
}
我把 final boolean [] 因为只有一个布尔值我得到一个错误:
"Variable is accessed from within an inner class, needs to be declared final."
一旦我宣布它是最终的:
"Can not assign a value to final variable"
所以我必须把它转换成一个数组。 我希望它是一个布尔方法,不要在“是”内实现删除,因为我想在其他方法中重用它。
【问题讨论】:
-
愚蠢的问题但是:你为什么使用布尔数组?
-
试试这个。我建议您使用以下链接中的方法并在正面按钮实现中执行删除。 stackoverflow.com/questions/2115758/…
-
@FrédéricLetellier:我怀疑这是因为如果只使用
final boolean那么 onClick 将无法修改值,而数组中的值可以。 -
@vidulaJ 同意,我这样编码
-
您的方法不会等待您的对话框被关闭。所以在 onclick 监听器中做你的事情。
标签: android button dialog confirmation