public class MainActivity extends WanAndroidBaseActivity {
@BindView(R.id.navigationView)
BottomNavigationView bottomNavigationView;
private List<Fragment> fragmentList;
private FragmentTransaction transaction;
private int lastFragment;
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void initView() {
initFragment();
lastFragment = 0;
// replace(int,fragment): 替换一个已被添加进视图容器的Fragment,缺点是每次都会重新初始化加载
transaction.replace(R.id.mainContainer, fragmentList.get(lastFragment));
// show(fragment): 显示一个存在fragment
// hide(fragment): 隐藏一个存在的fragment
transaction.show(fragmentList.get(lastFragment));
// 提交事务
transaction.commit();
bottomNavigationView.setOnNavigationItemSelectedListener(menuItem -> {
switch (menuItem.getItemId()) {
case R.id.menu_home:
if (lastFragment != 0) {
switchFragment(lastFragment, 0);
lastFragment = 0;
}
break;
case R.id.menu_knowledge_hierarchy:
if (lastFragment != 1) {
switchFragment(lastFragment, 1);
lastFragment = 1;
}
break;
case R.id.menu_wechat_sub:
if (lastFragment != 2) {
switchFragment(lastFragment, 2);
lastFragment = 2;
}
break;
case R.id.menu_project:
if (lastFragment != 3) {
switchFragment(lastFragment, 3);
lastFragment = 3;
}
break;
case R.id.menu_me:
if (lastFragment != 4) {
switchFragment(lastFragment, 4);
lastFragment = 4;
}
break;
default:
return true;
}
return true;
});
}
private void initFragment() {
fragmentList = new ArrayList<>();
fragmentList.add(new HomeFragment());
fragmentList.add(new HomeFragment());
fragmentList.add(new HomeFragment());
fragmentList.add(new HomeFragment());
fragmentList.add(new HomeFragment());
transaction = getSupportFragmentManager().beginTransaction();
}
/**
* 切换Fragment
*
* @param lastFragment
* @param currentIndex
*/
private void switchFragment(int lastFragment, int currentIndex) {
// hide(fragment): 隐藏fragment
transaction.hide(fragmentList.get(lastFragment));
if (!fragmentList.get(currentIndex).isAdded()) {
// add(): 像Activity state中添加一个Fragment
// remove(): 像Activity state中移除一个Fragment
transaction.add(R.id.mainContainer, fragmentList.get(currentIndex));
}
transaction.show(fragmentList.get(currentIndex));
// commitAllowingStateLoss: 和commit一样,但是允许Activity的状态保存之后提交
transaction.commitAllowingStateLoss();
}
}
注意Fragment中的几个方法的使用
网友评论