在另一个线程上完成网络请求后,我的 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/