我想创建一个在屏幕上显示带有2个按钮的对话框的函数,如果用户按OK,则返回1,如果用户按Cancel,则返回0。
public class CDlg {
static int ShowConfirm(String caption, String msg, Context context) {
int rez;
AlertDialog.Builder delAllDialog = new AlertDialog.Builder(context);
delAllDialog.setTitle(caption);
TextView dialogTxt_id = new TextView(context);
LayoutParams dialogTxt_idLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dialogTxt_id.setLayoutParams(dialogTxt_idLayoutParams);
dialogTxt_id.setText(msg);
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(dialogTxt_id);
delAllDialog.setView(layout);
delAllDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
rez = 1;
}
});
delAllDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
rez = 0;
}
});
delAllDialog.show();
return rez;
}
}
我现在确定自己做对了,因为我不知道如何将结果从较差的类传递给外部的类。有错误讯息
Cannot refer to a non-final variable rez inside an inner class defined in a different method
因此,我想使用该功能,如下所示:
if (CDlg.ShowConfirm("User confirmation","Delete?",this)==1){
...
}
最佳答案
你不能那样做。 ShowConfirm
仅可以显示对话框。当用户单击“确定”或“取消”按钮时,才可以执行所需的操作:
public class CDlg {
void ShowConfirm(String caption, String msg) {
AlertDialog.Builder delAllDialog = new AlertDialog.Builder(this);
delAllDialog.setTitle(caption);
TextView dialogTxt_id = new TextView(this);
LayoutParams dialogTxt_idLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dialogTxt_id.setLayoutParams(dialogTxt_idLayoutParams);
dialogTxt_id.setText(msg);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(dialogTxt_id);
delAllDialog.setView(layout);
delAllDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
handleButtonClick(1);
}
});
delAllDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
handleButtonClick(2);
}
});
delAllDialog.show();
}
void handleButtonClick(int rez) {
switch(rez) {
case 1: ..... break;
case 2: ..... break;
.....
}
}
}
在这里,
if (CDlg.ShowConfirm("User confirmation","Delete?",this)==1)
语句在Android中是无用的,因为ShowConfirm不会等到用户按下按钮。相反,只需调用
ShowConfirm("User confirmation","Delete?");
在onClick
中实现适当的代码即可。