Android 如果 Fragment 被销毁,我如何取消由 DialogFragment 创建的 AlertDialog?

标签 android android-fragments android-alertdialog

我有一个有登录按钮的 Activity ,登录按钮有一个异步任务,应该在任务开始前显示一个正在加载的 AlertDialog,并在完成时关闭对话框并退出到另一个 Activity 。

我需要它来处理方向变化,但如果在线程运行时发生方向, fragment 将被销毁,并且在 onPostExecute() 中调用 DialogFragment.dismiss 会给我一个空指针异常。我该怎么办?

在执行前

FragmentManager fm = getFragmentManager();
TestDiag alertFrag = new TestDiag();
alertFrag.show(fm, "Alert_Dialog");

在 PostExecute() 上

FragmentManager fm = getFragmentManager();
TestDiag alertFrag2= (TestDiag) fm.findFragmentByTag("Alert_Dialog");
alertFrag2.dismiss();

编辑:我试过在保留实例上设置为真,它可以工作,但也不起作用。

最佳答案

我只是锁定方向,直到我的 AsyncTask 完成,onPreExecute() -> 锁定和 onPostExecute() -> 释放。

public class Device {

public static void lockOrientation(Activity activity) {
    Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    int rotation = display.getRotation();
    int tempOrientation = activity.getResources().getConfiguration().orientation;
    int orientation = 0;
    switch(tempOrientation)
    {
    case Configuration.ORIENTATION_LANDSCAPE:
        if(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90)
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        else
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
        break;
    case Configuration.ORIENTATION_PORTRAIT:
        if(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270)
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        else
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
    }
    activity.setRequestedOrientation(orientation);
}





public static void releaseOrientation(Activity activity) {
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}

如果你真的想在任务运行时允许方向改变:Using AsyncTask with progress dialogs and device rotation.

关于Android 如果 Fragment 被销毁,我如何取消由 DialogFragment 创建的 AlertDialog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19060443/

相关文章:

java - 如果我在 IntentService 中使用 AsyncTask 会发生什么?

安卓更新界面

android - 如何在 android 中加载 .pdf 或 .doc 文件

android - FragmentManager、LocalActivityManager 和 TabHost.setup()

android - 我无法关闭自定义的警报对话框

Android AlertDialog 不显示单选按钮或消息

android - 无法在 Android 上显示 AlertDialog,因为我收到 NullPointerException

javascript - 设备运动事件未在从跨源 iframe chrome 62 打开的选项卡中触发

java - 我的 fragment 不会显示在我的 Activity 中

android - 没有提交的 fragment 事务