我已经在活动中实现了导航抽屉。我的应用中有3-4个片段。
假设有3个片段: fragment_1,fragment_2,fragment_3
启动应用程序时,Fragment_1已加载,然后使用导航抽屉转到另一个片段。
所以就像
fragment_1-> fragment_2-> fragment_3-> fragment_1-> fragment_3
现在,当我按返回按钮时,就像
fragment_3-> fragment_1-> fragment_3-> fragment_2-> fragment_1
但是,我想要的是,如果我在钥匙后我身边的任何地方,我 始终导航到fragment_1。
我正在使用以下代码导航到另一个片段: -
nav_menu_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
switch (position) {
case 0:
DashboardFragment dashboardFragment = new DashboardFragment();
fragmentTransaction.replace(R.id.mainContainer, dashboardFragment, dashboardFragment.getClass().getName());
break;
case 1:
ProfileFragment profileFragment = new ProfileFragment();
fragmentTransaction.replace(R.id.mainContainer, profileFragment, profileFragment.getClass().getName());
fragmentTransaction.addToBackStack(null);
break;
case 2:
ContactUsFragment contactUsFragment = new ContactUsFragment();
fragmentTransaction.replace(R.id.mainContainer, contactUsFragment, contactUsFragment.getClass().getName());
fragmentTransaction.addToBackStack(null);
break;
case 3:
AboutUsFragment aboutUsFragment = new AboutUsFragment();
fragmentTransaction.replace(R.id.mainContainer, aboutUsFragment, aboutUsFragment.getClass().getName());
fragmentTransaction.addToBackStack(null);
break;
default:
break;
}
fragmentTransaction.commit();
drawer.closeDrawer(GravityCompat.START);
}
});
请帮助...
@Override
public void onBackPressed() {
if(!(getSupportFragmentManager().findFragmentById(R.id.mainContainer) instanceof DashboardFragment))
{
DashboardFragment dashboardFragment = new DashboardFragment();
fragmentTransaction.replace(R.id.mainContainer, dashboardFragment, dashboardFragment.getClass().getName());
}else {
super.onBackPressed();
}
}
将此方法用于主要活动将解决您的问题。
我已经更改了您的代码中的下一行,并且效果很好
替换:
fragmentTransaction.replace(R.id.mainContainer, dashboardFragment,
dashboardFragment.getClass().getName());
with:
getSupportFragmentManager().beginTransaction().replace(R.id.mainContainer,
dashboardFragment).commit();