android - 如何从自定义对话框类关闭 Activity ?

标签 android class android-activity dialog

我有一个 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/

相关文章:

安卓 Scala 和 Gradle

c++ - 如何将 void 指针转换为类数组

android - 没有焦点的自定义对话框

C++ - 类声明中的两个名称(宏)

android - 这指向什么错误 - "new_window_surface returns 0x3000"

java - Android 无法实例化 Activity : Didn't find class on path

android - 将多个嵌套列表保存到房间数据库中

java - 将变量设置为android中的文件夹路径Environment.DIRECTORY_DOWLOAD

android - 从未调用过 Facebook 示例应用程序的回调

perl - 你能有一个没有 .pm 标签的 Perl 类吗?