android - 什么时候使用 FragmentManager.isDestroyed()?为了避免 IllegalStateException?

标签 android fragmentmanager

在另一个线程上完成网络请求后,我的 Activity 中有一个监听器替换了一个 Fragment。所以这个监听器调用了这样一行代码:

getFragmentManager().beginTransaction().replace(R.id.container, fragment, fragmentTag).commit();

这行代码中的 commit() 偶尔会抛出 IllegalStateException。根据the docs ,

A transaction can only be committed with this method prior to its containing activity saving its state. If the commit is attempted after that point, an exception will be thrown. This is because the state after the commit can be lost if the activity needs to be restored from its state. See commitAllowingStateLoss() for situations where it may be okay to lose the commit.

在调查这个问题时,我发现了 FragmentManager.isDestroyed()方法。 javadocs 阅读:

Returns true if the final Activity.onDestroy() call has been made on the FragmentManager's Activity, so this instance is now dead.

我想我对 FragmentManager 的 Activity 实例已死的含义有点困惑。我们什么时候应该使用 FragmentManager.isDestroyed()?在提交替换 FragmentTransaction 之前检查它会避免 IllegalStateException 吗?

最佳答案

我的代码如下所示。执行时,要么工作正常并显示我想要的 fragment ,要么我收到指示 .isDestroyed() 为真的日志消息。如果我删除对 .isDestroyed() 的检查,则 ft.commit() 将抛出 IllegalStateException。

此解决方案可防止由此产生的崩溃,但不一定能解决它首先出现的潜在时间问题。

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragementTransaction;

public class CallingCard extends Fragment
{
    // ... some stuff for my fragment ...
}

public class MyFragment extends Fragment
{
    public void showCallingCard() {
        CallingCard callingCard = new CallingCard();
        FragmentManager fm = parent.getSupportFragmentManager();

        // ensure serialization of fragment transactions
        fm.executePendingTransactions();

        if (!fm.isDestroyed()) {
            // attempt to display fragment
            FragementTransaction ft = fm.beginTransaction();
            ft.replace(R.id.fragPlaceHolder, callingCard);
            ft.commit();
        } else {
            Log.e("tag", "fm.isDestroyed() was true");
        }
    }
}

关于android - 什么时候使用 FragmentManager.isDestroyed()?为了避免 IllegalStateException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814457/

相关文章:

kotlin - 移至androidX后出现“inferred type is FragmentManager? but FragmentManager was expected”错误

javascript - 在 Release模式下运行 Android Cordova 应用程序时,Ajax 调用失败

java - 无法在 Android 中从 URL 加载照片

java - Android 异常尝试调用虚方法 'int android.content.Context.checkPermission(java.lang.String, int, int)

android - 隐藏 fragment 留下空白

android - 没有支持库的 BetterPickers

android - 适用于 Android 和 iOS 的 2D 跨平台游戏引擎?

android - 从 GPS 获取位置并在 android 中的谷歌地图上设置标记

android - popBackStackImmediate 在当前 fragment 事务未添加到后台堆栈时不显示 fragment

android - 检测 DialogFragment 中的用户不活动并在一段时间后注销