gpt4 book ai didi

Android:什么时候使用FragmentTransaction.remove合适?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:32:35 24 4
gpt4 key购买 nike

我以为我已经明白您应该在 onCreate() 中调用 FragmentTransaction.add() 并在 onDestroy() 中调用 FragmentTransaction.remove()。我的应用程序在 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() 中添加 fragment 。 Android 在配置更改时自动重新创建 fragment 。因此,onCreate() 应该在添加之前检查 fragment 是否已经存在:

  @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:什么时候使用FragmentTransaction.remove合适?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17329824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com