简体   繁体   中英

Adding back button to fragment

I have a bottom navigation bar that contains 4 fragments and when a tab is selected a new instance of that fragment is loaded.

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
    = new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment fragment = null;
    switch (item.getItemId()) {
        case R.id.navigation_home:
            fragment = HomeFragment.newInstance();
            break;
        case R.id.navigation_cards:
            fragment = CardsFragment.newInstance();
            break;
        case R.id.navigation_deals:
            fragment = DealsFragment.newInstance();
            break;
        case R.id.navigation_settings:
            fragment = SettingsFragment.newInstance();
            break;
    }
    if (fragment != null) {


        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.content, fragment);
        fragmentTransaction.commit();
    }
    return true;
}
};

Now in my HomeFragment there is a RecyclerView that On Item Select it opens a new Fragment:

   myViewHolder.cardView.setOnClickListener(view -> {
            System.out.println("clicked");

            Fragment fragment = new TargetDetailsFragment();
            FragmentTransaction ft = ((AppCompatActivity) context).getSupportFragmentManager()
                    .beginTransaction();
            ft.replace(R.id.content, fragment).addToBackStack(null);
            ft.commit();





        });

I want to add a back button to the TargetDetails Fragments that takes you back to the home page when selected and I attempted doing that by implementing OnBackStackChangedListener in the Main activity

@Override
public void onBackStackChanged() {
    shouldDisplayHomeUp();
}

public void shouldDisplayHomeUp(){
    //Enable Up button only  if there are entries in the back stack
    boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
    getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}

@Override
public boolean onSupportNavigateUp() {
    //This method is called when the up button is pressed. Just the pop back stack.
    getSupportFragmentManager().popBackStack();
    return true;
}

}

but the problem is when I click on it its reloads the HomeFragment Again but I simply want it to go back to the saved instance of that Fragment

By adding below code in your Activity. The fragment back stack can be managed.

@Override
    public void onBackPressed() {

        int count = getFragmentManager().getBackStackEntryCount();

        if (count == 0) {
            super.onBackPressed();
            //additional code
        } else {
            getFragmentManager().popBackStack();
        }

    }

Hello @Bolu Okunaiya i think you should try this it will help you to manage backstack to desired fragment without loading same fragment again.

For Stop loading previous fragment you should use "add" instead of "replace" with your FragmentTransaction

Here is my code that I have used for the ViewPager , the idea is to see if the current page number is 0 than to proceed super.onBackPressed(); otherwise go to the previous fragment:

@Override
public void onBackPressed() {
    if(vpPager.getCurrentItem()!=0) {
        vpPager.setCurrentItem(vpPager.getCurrentItem()-1, true);
    } else {
        super.onBackPressed();
    }
}

Inside your MainActivity

@Override
        public void onBackStackChanged() {
            //shouldDisplayHomeUp();
            Fragment currentFragment = getActivity().getFragmentManager()
                              .findFragmentById(R.id.fragment_container);

          if (currentFragment instanceof TargetDetails) {
                  Log.v(TAG, "your current fragment is TargetDetails");
                  popBackStackImmediate(); //<<<< immediate parent fragment will open,which is your HomeFragement

                 }

        }

To use popBackStackImmediate() you need to *replace FragmentA with FragmentB and use addToBackstack() before commit() .

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