gpt4 book ai didi

android - 具有返回值的函数中的 AlertDialog

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:24 24 4
gpt4 key购买 nike

我写了一个返回值为 int 类型的函数,在这个函数中我需要弹出一个带有两个按钮的 AlertDialog。当点击"is"按钮时,函数返回0,“否”按钮返回-1。

public int Func(){
final AlertDialog d=new AlertDialog.Builder(mContext).setTitle("Warning").setCancelable(false).setMessage
(alert)
.setPositiveButton("Yes",mListener).setNegativeButton("No",mListener).create();
d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
d.show();
if(mWhich.getWhich()==-1) //the "yes" button was clicked
return 0;
else //the "no" button was clicked
return -1;
}

mWhich是用来记录用户选择的类

private DialogInterface.OnClickListener mListener =
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
mWhich.setWhich(which);
}
};

现在的问题是代码

if(mWhich.getWhich()==-1)
return 0;
else
return -1;

在用户点击yes or no按钮之前执行了,怎么办??

最佳答案

据我了解,您的代码看起来类似于

// some code
int result = Func();
DoSmthWithResult(result);
// some code

您的 Func 正在 UI 线程上运行,因此在您创建对话框后它会继续执行并返回 mWich 的初始值。您应该改为从 onClickListener 调用 DoSmthWithResult:

private DialogInterface.OnClickListener mListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DoSmthWithresult(which == -1 ? 0 : -1);
}
};

现在 DoSmthWithResult 将在用户按下"is"或“否”按钮后执行。

关于android - 具有返回值的函数中的 AlertDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13679823/

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