其他分享
首页 > 其他分享> > Android:何时使用FragmentTransaction.remove是否合适?

Android:何时使用FragmentTransaction.remove是否合适?

作者:互联网

我以为我已经明白你应该在onCreate()和onDestroy()中的FragmentTransaction.remove()中调用FragmentTransaction.add().我的应用程序在onDestroy()崩溃时出现此错误:

06-26 15:25:50.213: E/AndroidRuntime(579): java.lang.RuntimeException: Unable to destroy activity {com.myapp/com.myapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed

如果不在onCreate / onDestroy()中我什么时候调用这些东西?

解决方法:

My problem with that is that when I switch to my horizontal view, and then back to my vertical view, I now have a duplicate layout for at least one of the nested fragments.

我的猜测是因为你总是在onCreate()中添加片段. Android会自动在配置更改时重新创建片段.因此,onCreate()应该在添加之前检查片段是否已经存在:

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

    if (getSupportFragmentManager().findFragmentById(android.R.id.content)==null) {
      getSupportFragmentManager().beginTransaction()
                                 .add(android.R.id.content,
                                      new RotationFragment()).commit();
    }
  }

标签:android,crash,fragmenttransaction
来源: https://codeday.me/bug/20190517/1122067.html