1

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

  • Hello and welcome to StackOverflow. What have you done and what is your problem ? – Bruno May 12 '21 at 07:47
  • Please refer to this answer for your question - https://stackoverflow.com/questions/7992216/android-fragment-handle-back-button-press – Sasaki May 12 '21 at 08:12

2 Answers2

0

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.

Omicron
  • 365
  • 4
  • 9
0

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

        }

    }
Akshay Rajput
  • 173
  • 1
  • 6