为了账号安全,请及时绑定邮箱和手机立即绑定

无法处理导航片段中的后退按钮

无法处理导航片段中的后退按钮

狐的传说 2021-10-28 17:24:42
在我的应用程序中,我使用导航抽屉转到不同的片段。但是当我点击后退按钮时,它会退出应用程序。我希望当在任何片段中单击后退按钮时,它会导航到主页片段。drawer_activity.java 导航不同的片段public boolean onNavigationItemSelected(MenuItem item) {    Fragment fragment = null;    // Handle navigation view item clicks here.    int id = item.getItemId();    if (id == R.id.home) {        toolbar.setTitle("HOME");        fragment = new HomeFragment();    } else if (id == R.id.wishlist) {        toolbar.setTitle("YOUR WISHLIST");    } else if (id == R.id.order) {        toolbar.setTitle("YOUR ORDER HISTORY");    } else if (id == R.id.cart) {        toolbar.setTitle("YOUR CART");    } else if (id == R.id.nav_share) {        toolbar.setTitle("HOME");    } else if (id == R.id.account) {        toolbar.setTitle("YOUR ACCOUNT");    } else if (id == R.id.logout) {        finish();        SharedPrefManager.getInstance(getApplicationContext()).logout();    }    if (fragment != null) {        FragmentManager fragmentManager = getSupportFragmentManager();        FragmentTransaction ft = fragmentManager.beginTransaction();        ft.replace(R.id.content, fragment);        ft.commit();    }    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);    drawer.closeDrawer(GravityCompat.START);    return true;   }主页片段.javapublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {    View rootView = inflater.inflate(R.layout.activity_home, container,false);    //getting the recyclerview from xml    recyclerView = (RecyclerView) rootView.findViewById(R.id.recylcerView);    recyclerView.setHasFixedSize(true);    recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));        }在此片段中,当从回收站视图中单击一个项目时,它会导航到另一个片段。当我单击手机的后退按钮时,该片段从应用程序退出。我想要当点击后退按钮时它总是回到主页片段,只有从主页片段应用程序退出时点击后退按钮。
查看完整描述

1 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

好的!!只需复制此代码并粘贴,您就会得到您想要的。ft.addToBackStack(null);是这里的关键。


Fragment fragment = new ProductListFragment();

FragmentManager fragmentManager = getActivity().getSupportFragmentManager();

FragmentTransaction ft = fragmentManager.beginTransaction();

ft.addToBackStack(null);

ft.replace(R.id.content, fragment);

ft.commit();


查看完整回答
反对 回复 2021-10-28
  • 1 回答
  • 0 关注
  • 118 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信