我想通过片段替换操作保留视图,并注意到一个奇怪的错误:
片段的View通过替换操作销毁后,它仍然有一个父节点,但是,父节点在其子节点之间没有视图。
private View view;
@Override
public View onCreateView(...) {
if (view == null) {
view = // ... inflate view
} else {
// at this point, view has mParent, but can't be removed
// because the parent does not have it among its children
}
return view;
}
@Override
public void onDestroyView() {
// I could remove the view from its parent here manually,
// however, it will cause fragment's content to disappear before
// the replace animation ends
}
请注意视图如何通过mParent
引用其父级,但父级为mChildrenCount
。
这会导致片段事务在尝试重用视图时因异常而崩溃:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first
。我发现这种行为异常错误,因为它使片段的视图处于不可用状态。
如果有人遇到此问题,请分享您的解决方法。我想出了一个临时的反思解决方案:
@Override
public View onCreateView(...) {
if (view == null) {
view = // ... inflate view
} else {
// clear parent reference (because SDK fails to do it)
Field f = View.class.getDeclaredField("mParent");
f.setAccessible(true);
f.set(view, null);
}
return view;
}