我想将AlertDialog封装到一个函数中,这样我就可以使我的代码更具可读性和杂乱性。但我无法使此功能返回结果
public int ShowMessageBox(Context context, String title, String message){
int result;
new AlertDialog.Builder(context)
.setTitle(title.toString())
.setMessage(message.toString())
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
result = 1; //error here
//dialogInterface.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
result = 2; //error here
//dialogInterface.dismiss();
}
})
.show();
return result;
}
我如何返回结果,以便我可以将此功能用作
int i = ShowMessageBox(MainActivity.this, "Title", "Message");
if (i == 1)
do this
else if (i == 2)
do that
答案 0 :(得分:0)
它是异步的,你应该保持这样。您可以制作Interface
并将其传递给您的方法。这将是你的界面:
public interface MessageBoxListener {
void result(int result);
}
您更新的方法:
public void showMessageBox(Context context, String title, String message, final MessageBoxListener listener) {
new AlertDialog.Builder(context)
.setTitle(title.toString())
.setMessage(message.toString())
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
listener.result(1);
//dialogInterface.cancel();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
listener.result(2);
//dialogInterface.dismiss();
}
})
.show();
}
要使用它,你可以这样做:
showMessageBox(MainActivity.this, "Title", "Message", new MessageBoxListener() {
@Override
public void result(int result) {
if (result == 1)
// Do something
else
// Do something else
}
});