Car*_*ine 5 android android-alertdialog
我编写了一个返回值为int的函数,在这个函数中我需要弹出一个带有两个按钮的AlertDialog.单击"是"按钮时,函数返回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;
}
Run Code Online (Sandbox Code Playgroud)
mWhich是用于记录用户选择的类
private DialogInterface.OnClickListener mListener =
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mWhich.setWhich(which);
}
};
Run Code Online (Sandbox Code Playgroud)
现在问题是代码
if(mWhich.getWhich()==-1)
return 0;
else
return -1;
Run Code Online (Sandbox Code Playgroud)
在用户点击是或否按钮之前执行,我该怎么办?
我认为您这样做的方式是不可能的,因为Func()可能会在用户单击任一按钮之前完成执行。方法执行完成后,不可能更改其返回值。
由于您已经在which使用mWhich.setWhich(which);. 您可以稍后使用另一个函数读取该值。
private DialogInterface.OnClickListener mListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mWhich.setWhich(which);
}
};
public void showDialog() {
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();
}
public int func() {
if (mWhich.getWhich() == -1)
// the "yes" button was clicked
return 0;
else
// the "no" button was clicked
return -1;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2314 次 |
| 最近记录: |