gpt4 book ai didi

android - 总是返回到主 fragment onBackpressed

转载 作者:行者123 更新时间:2023-11-30 00:50:00 30 4
gpt4 key购买 nike

我已经在 Activity 中实现了 Navigation Drawer。我的应用程序中有 3-4 个 fragment 。

假设有 3 个 fragment :Fragment_1、Fragment_2、Fragment_3

当我启动我的应用程序时,Fragment_1 被加载,我使用抽屉导航转到另一个 fragment 。

原来如此

fragment _1 -> fragment _2 -> fragment _3 -> fragment _1 -> fragment _3

现在,当我按下后退按钮时,它就像

fragment _3 -> fragment _1 -> fragment _3 -> fragment _2 -> fragment _1

But, I want something like if wherever i am when i press back key, i navigate back to Fragment_1 always.

我正在使用下面的代码导航到另一个 fragment :-

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();
}
}

使用此方法进入主要 Activity 将解决您的问题。

关于android - 总是返回到主 fragment onBackpressed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219699/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com