在我的應用程序中,我使用導航抽屜轉到不同的片段。但是當我點擊后退按鈕時,它會退出應用程序。我希望當在任何片段中單擊后退按鈕時,它會導航到主頁片段。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();
添加回答
舉報
0/150
提交
取消