简体   繁体   中英

Back press to the previous fragment or home in android

I am trying to do back press moving to the previous fragment or to home fragment in my app, kindly guide me to achieve it. Thanks in advance

Add addToBackstack(null) When You change fragments in your activity, like so:

getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Fragment()).addToBackStack(null).commit();

Whenever you add a fragment to backstack it will be poped from it when You press back button and app will return to previous fragment that was also added to backstack.

I use this code to navigate between the fragments

this method is responsible to load require fragment

public void loadFragment(Fragment fragment, String tag) {
        if (fragment != null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container, fragment, tag)
                    .commit();
        }
    }

to load a fragment use:

loadFragment(new HomeFragment(), "HomeFragment");

handle back press like this in your activity:

@Override
    public void onBackPressed() {
        HomeFragment homeFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag("HomeFragment");
        SearchFragment searchFragment = (SearchFragment) getSupportFragmentManager().findFragmentByTag("ConnectionFragment");
        NotificationFragment notificationFragment = (NotificationFragment) getSupportFragmentManager().findFragmentByTag("NotificationFragment");

        if (homeFragment != null && homeFragment.isVisible()) {
            finish();
        }
        if (searchFragment != null && searchFragment.isVisible()) {
            loadFragment(new HomeFragment(), "HomeFragment");
            navigationView.setSelectedItemId(R.id.navigation_home);

        }
        if (notificationFragment != null && notificationFragment.isVisible()) {
            loadFragment(new HomeFragment(), "HomeFragment");
            navigationView.setSelectedItemId(R.id.navigation_home);

        }

    }

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