我已经创建了一个底部导航视图。效果很好,除了当我使用addToBackStack(null)
处理片段时,我有片段[A] [B] [C]和[D],单击后退键可循环浏览BackStack中的所有片段。这个我不要每当我按返回键时,我只希望返回片段[A]。
如果我移除addToBackStack(null)
,请按返回键关闭片段。
我尝试了许多解决方案,但没有把事情做好。请我需要帮助。 我的代码写在下面;
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_nav_view);
bottomNavigationView.setOnNavigationItemSelectedListener(AtomsNavListener);
//Keep home fragment selected
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new HomeFragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener AtomsNavListener = new
BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.bottom_home:
selectedFragment = new HomeFragment();
break;
case R.id.bottom_book_appointment:
selectedFragment = new ConnectADocFragment();
break;
case R.id.bottom_history:
selectedFragment = new AppointmentHistoryFragment();
break;
case R.id.bottom_profile:
selectedFragment = new ProfileFragment();
break;
}
navigateToFragment(selectedFragment);
return true;
}
};
private void navigateToFragment(Fragment selectedFragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, selectedFragment)
.addToBackStack(null)
.commit();
}