[英]Fragment not attached to Activity, best solution?
I have an Activity with google map, and a fragment, with address (start/stop) fields in it. 我有一个带有google map的Activity和一个带有地址(开始/停止)字段的片段。
When LocationManager
return user's location first time, I'm try to update start field in addresses fragment. 当
LocationManager
第一次返回用户的位置时,我尝试更新地址片段中的起始字段。
But sometimes I get the exception: java.lang.IllegalStateException: Fragment CoordinatesFragment not attached to Activity
但有时我会遇到异常:
java.lang.IllegalStateException: Fragment CoordinatesFragment not attached to Activity
And I don't understand why. 而且我不明白为什么。 I know that there are method
Fragment.isAdded()
, wich I can use, but it seems not a best way to solve the problem. 我知道可以使用
Fragment.isAdded()
方法,但这似乎并不是解决问题的最佳方法。
Also sometimes I get this exception when try to restore state (in onRestoreInstanceState(Bundle state)
i get data and in onMapLoaded()
try to use) 也有时在尝试还原状态时出现此异常(在
onRestoreInstanceState(Bundle state)
我获取数据,在onMapLoaded()
尝试使用)
Check this; 检查一下; http://developer.android.com/reference/android/app/Fragment.html#isAdded()
http://developer.android.com/reference/android/app/Fragment.html#iwego()
if(!isAdded()) {
return;
}
private void setFragment(Fragment fragmentToSet, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = manager.findFragmentByTag(tag);
if (savedInstanceState == null) {
if (fragment != null && !fragment.isAdded()) {
transaction.replace(R.id.home_container, fragment, tag);
} else if (fragmentToSet != null && !fragmentToSet.isAdded()) {
transaction.replace(R.id.home_container, fragmentToSet, tag);
}
}else{
transaction.replace(R.id.home_container, fragment, tag);
}
transaction.commitAllowingStateLoss();
manager.executePendingTransactions();
}
Try using this function to set the fragment in your activity. 尝试使用此功能在您的活动中设置片段。 Its working good for me.
它的工作对我有好处。 You can save the savedInstanceState from your activity's onCreate
您可以从活动的onCreate中保存savedInstanceState
If you could use RxJava 2, you could have the result of LocationManager in an Observable cached, and the Fragment could subscribe for the result. 如果可以使用RxJava 2,则可以将LocationManager的结果缓存在Observable中,并且Fragment可以预订结果。
If the result have arrived and the Fragment is not yet attached, the Fragment will recieve the result when it is attached. 如果结果已到达且尚未附加片段,则片段将在附加后接收结果。 Else it will receive it instantly.
否则它将立即收到。
I recommend for you to learn how RxJava can be used to tackle such problems. 我建议您学习如何使用RxJava解决此类问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.