gpt4 book ai didi

java - 如何从单独的类中的对话框返回值

转载 作者:行者123 更新时间:2023-12-01 14:48:51 26 4
gpt4 key购买 nike

我想创建一个函数,在屏幕上显示一个带有 2 个按钮的对话框,如果用户按下“确定”,则返回 1;如果用户按下“取消”,则返回 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("用户确认","删除?",this)==1) 语句在 Android 中没有用处,因为 ShowConfirm 不会等到用户按下一个按钮。

只需调用 ShowConfirm("用户确认","删除?"); 并在 onClick 中实现适当的代码即可。

关于java - 如何从单独的类中的对话框返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15096896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com