fix bugs.10

This commit is contained in:
2025-12-06 10:32:31 +08:00
parent 97dd450074
commit 87b73e7ca2

View File

@@ -438,7 +438,7 @@ public class RoomFragment extends BaseMvpFragment<RoomPresenter, FragmentRoomBin
if (currentFragment == null){
performFragmentReplacement(newFragment, R.id.container);
}else {
switchFragmentSafely(newFragment, R.id.container);
switchFragment(newFragment, R.id.container);
}
} else {
LogUtils.e("newFragment==null");
@@ -458,47 +458,34 @@ public class RoomFragment extends BaseMvpFragment<RoomPresenter, FragmentRoomBin
private Fragment currentFragment = null;
private boolean isReplacing = false;
private void switchFragmentSafely(Fragment newFragment, int containerId) {
if (isReplacing) return;
isReplacing = true;
private void switchFragment(Fragment newFragment, int containerId) {
if (!isAdded() || newFragment == null) return;
View container = getView().findViewById(containerId);
if (container == null) {
isReplacing = false;
return;
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
// 1. 添加新 Fragment
if (!newFragment.isAdded()) {
ft.add(containerId, newFragment, newFragment.getClass().getSimpleName());
} else if (newFragment.getView() == null) {
ft.attach(newFragment); // 确保 view 被创建
}
container.post(() -> {
if (!isAdded()) {
isReplacing = false;
return;
}
// 2. 显示新 Fragment
ft.show(newFragment);
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
// 3. 隐藏旧 Fragment
if (currentFragment != null && currentFragment != newFragment) {
ft.hide(currentFragment);
}
// 1⃣ 如果新 Fragment 没添加过,先 add
if (!newFragment.isAdded()) {
ft.add(containerId, newFragment, newFragment.getClass().getSimpleName());
}
ft.commitNowAllowingStateLoss(); // 立即提交
// 2⃣ 显示新 Fragment
ft.show(newFragment);
// 3⃣ 隐藏旧 Fragment
if (currentFragment != null && currentFragment != newFragment) {
ft.hide(currentFragment);
}
ft.commitAllowingStateLoss(); // 使用异步提交,避免阻塞 UI
// 4⃣ 更新引用
currentFragment = newFragment;
isReplacing = false;
});
currentFragment = newFragment;
}
// RoomFragment.java
@@ -1077,15 +1064,4 @@ public class RoomFragment extends BaseMvpFragment<RoomPresenter, FragmentRoomBin
}
}
private void ensureFragmentView(Fragment f) {
if (f.getView() == null) {
LogUtils.e("Fragment view is null, try to force attach: " + f.getClass().getSimpleName());
// 强制触发一次 view 的创建
// getChildFragmentManager()
// .beginTransaction()
// .attach(f)
// .commitNowAllowingStateLoss();
}
}
}