简体   繁体   中英

Bottom navigation bar stop a fragment running when another one is opened

So I have no idea how to do this and even where to start, so if someone would be patient enough to explain how to do this I would be appreciated. I already looked up on google but what I found was too difficult to understand ( and I am pretty sure that it can be done way more easily.

I have 4 fragments (4 tabs on a bottom navigation bar) and I want to have only 1 running at the time. Now, I am pretty sure that I should use FragmentManager but I don't really know how to start to implement in my program.

Do I have to write all the FragmentTransaction code in the mainActivity? and after that how to keep goin? Is there a example code by any chance?

Disclaimer: I am a total noob in the android studio environment and I am also a student and I almost do everything as a school project.

You Can try this in your code. On the onNavigationItemSelected

@Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment = null;

        switch (item.getItemId()) {
            case R.id.navigation_home:
                fragment = new HomeFragment();
                break;

            case R.id.navigation_dashboard:
                fragment = new DashboardFragment();
                break;

            case R.id.navigation_notifications:
                fragment = new NotificationsFragment();
                break;

            case R.id.navigation_profile:
                fragment = new ProfileFragment();
                break;
        }

        return loadFragment(fragment);
    }

    private boolean loadFragment(Fragment fragment) {
        //switching fragment
        if (fragment != null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, fragment)
                    .commit();
            return true;
        }
        return false;
    }

I hope this can help You!

Thank You.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM