1

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

我需要它来处理方向更改,但是如果在线程运行时发生方向,则片段被破坏并且调用 DialogFragment.dismissonPostExecute()会给我一个空指针异常。我应该怎么办?

在预执行

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();

编辑:我已经尝试在保留实例上设置 true 并且它可以工作,但它也不起作用。

4

1 回答 1

1

I simply lock orientation until my AsyncTask is completed, onPreExecute() -> lock and onPostExecute() -> release.

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);
}

}

If you really want to allow orientation change while task is running: Using AsyncTask with progress dialogs and device rotation.

于 2013-09-27T23:37:50.990 回答