我正在尝试将我的应用程序切换为使用对话框 fragment ,但是在对话框可见时旋转屏幕时出现应用程序崩溃。我可以在下面描述的一个非常简单的应用程序中重现这一点。在 Android Studio 中创建一个新项目并添加一个 DialogFragment,如下所示:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
        if (savedInstanceState == null) {
            (new Handler()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
                            .setMessage("Alert")
                            .setTitle("My Alert")
                            .create();
                    MyDialogFragment dialogFragment = new MyDialogFragment();
                    dialogFragment.setDialog(dialog);
                    dialogFragment.show(getSupportFragmentManager(), "dialog");

                }
            }, 1000);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }

        @Override
        public void onActivityCreated(Bundle savedState) {
            super.onActivityCreated(savedState);
        }
    }

    public static class MyDialogFragment extends DialogFragment {
        private Dialog mDialog;

        public MyDialogFragment() {
            super();
            mDialog = null;
        }

        @Override
        public void onCreate(Bundle state) {
            super.onCreate(state);
        }

        // Set the dialog to display
        public void setDialog(Dialog dialog) {
            mDialog = dialog;
        }

        // Return a Dialog to the DialogFragment.
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            return mDialog;
        }
    }
}

现在运行应用程序,在对话框出现后(加载后 1 秒),旋转屏幕。请注意,我只在上面的初始 onCreate 上创建对话框。

这是我得到的异常(exception):
01-30 11:19:40.199  31986-31986/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.testdialogs, PID: 31986
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testdialogs/com.example.testdialogs.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
            at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3758)
            at android.app.ActivityThread.access$900(ActivityThread.java:145)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5081)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at android.support.v4.app.DialogFragment.onActivityCreated(DialogFragment.java:368)
            at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1508)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086)
            at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1884)
            at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:566)
            at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
            at android.app.Activity.performStart(Activity.java:5241)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
            at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3758)
            at android.app.ActivityThread.access$900(ActivityThread.java:145)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5081)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)
            
            
            
            

我的 gradle 脚本如下所示:
apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.1"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:+'
}

这只是您创建新项目并使用最新的 android 支持 jar 时的标准构建脚本。

我可以在 DialogFragment 的 onCreate 方法中执行 setRetainInstance ,然后它不会崩溃,但对话框在旋转时被关闭。这显然比崩溃要好,但不是我想要的。

我不确定使用 DialogFragments 的首选方式是什么,但我从直接来自 google 的一些示例代码(对于 google service sdk)中得到了这个想法。我想他们知道他们在做什么,所以我会使用相同的概念。

最佳答案

我通过子类化 DialogFragment 类并覆盖接下来的两个生命周期回调方法解决了这个问题:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public void onDestroyView() {
    if (getDialog() != null && getRetainInstance()) {
        getDialog().setDismissMessage(null);
    }
    super.onDestroyView();
}

关于Android 支持 DialogFragment 在屏幕旋转时崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21465932/

10-12 06:00