private void switchFragment(Fragment fragment) {
if (fragment != mTempFragment) { //如果相等不用做任何操作 所以加了此判断
if (!fragment.isAdded()) { //判断是否添加过该Fragment
getSupportFragmentManager().beginTransaction().hide(mTempFragment).add(R.id.fragment_container, fragment).commit(); //如果没有添加过则添加
} else {
getSupportFragmentManager().beginTransaction().hide(mTempFragment).show(fragment).commit();//如果添加过则直接隐藏之前的Fragment并显示出来
}
mTempFragment = fragment;
}
}
使用
//根据个人喜好哈 不做强制要求
mFragmentSparseArray = new SparseArray<>();
mFragmentSparseArray.append(R.id.today_tab, NavFunFragment.getInstance());
mFragmentSparseArray.append(R.id.record_tab, NavSearchFragment.getInstance());
mFragmentSparseArray.append(R.id.contact_tab, NavMessageFragment.getInstance());
mFragmentSparseArray.append(R.id.settings_tab, NavMeFragment.getInstance());
//默认显示第一个
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, mTempFragment).commit();
mTabRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//使用方法
switchFragment(mFragmentSparseArray.get(checkedId));
}
});
效果