我有一个 AlertDialogUtils
类,它生成一个 AlertDialog
,以便在发生错误时可以从任何 Activity 调用它。问题是我无法从 createDialog()
方法中调用 finish()
作为“关闭”按钮的 onClickListener
。
有什么想法这可能吗?
AlertDialogUtils 类的代码:
public class AlertDialogUtils extends Dialog {
private Context mContext;
public AlertDialogUtils(Context context) {
super(context);
mContext = context;
}
public void CreateAlertDialog(String errorMessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(errorMessage)
.setCancelable(true)
.setNeutralButton("Dismiss", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mContext.finish();
//error here. Intend to close the activtiy that created this dialog and has the error
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity((Activity)mContext);
// The dialog utils is outside an activity. Need to set owner
alert.show();
}
}
最佳答案
可以请你尝试一下这个方法吗? :
interface ICloseActivity {
void close();
}
class MyActivityToClose extends Activity implements ICloseActivity {
public void close() {
finish();
}
}
// -------
public class AlertDialogUtils extends Dialog {
private Context mContext;
private ICloseActivity mICloseActivity;
public AlertDialogUtils(Context context, ICloseActivity aActivity) {
super(context);
mContext = context;
mICloseActivity = aActivity;
}
public void CreateAlertDialog(String errorMessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(errorMessage)
.setCancelable(true)
.setNeutralButton("Dismiss", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// mContext.finish();
//error here. Intend to close the activtiy that created this dialog and has the error
//TRY THIS please:
mICloseActivity.close();
}
});
AlertDialog alert = builder.create();
alert.setOwnerActivity((Activity)mContext);
// The dialog utils is outside an activity. Need to set owner
alert.show();
}
关于android - 如何从自定义对话框类关闭 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6949855/