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

在我的应用程序中,我使用导航抽屉转到不同的片段。但是当我点击后退按钮时,它会退出应用程序。我希望当在任何片段中单击后退按钮时,它会导航到主页片段。


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;

   }

主页片段.java


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


        }


在此片段中,当从回收站视图中单击一个项目时,它会导航到另一个片段。当我单击手机的后退按钮时,该片段从应用程序退出。我想要当点击后退按钮时它总是回到主页片段,只有从主页片段应用程序退出时点击后退按钮。


狐的传说
浏览 119回答 1
1回答

BIG阳

好的!!只需复制此代码并粘贴,您就会得到您想要的。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();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java