Fragment动态切换
private FragmentTransaction switchFragment(Fragment targetFragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (!targetFragment.isAdded()) {
//第一次使用switchFragment()时currentFragment为null,所以要判断一下
if (currentFragment != null) {
transaction.hide(currentFragment);
}
transaction.add(R.id.right_layout, targetFragment, targetFragment.getClass().getName());
} else {
transaction
.hide(currentFragment)
.show(targetFragment);
}
currentFragment = targetFragment;
return transaction;
}
Fragment显示和隐藏判断
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
isVisible = false;
} else {
isVisible = true;
}
}
注意第一次加载不会调用,在onCreateView中设置isVisible = true;