Adding back button to fragment

back button navigation in fragment android
android fragment back button example
how to use back button in android studio
finish fragment on back pressed
android action bar back button not working in fragment
return to previous fragment on back press
android fragment back button programmatically
how to go back from fragment to activity in android

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

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

Manage toolbar's navigation and back button from fragment in android, side_bar_container, which we add content to right after the above code. If I hit the back button in that case, it would be nice if it popped both fragments at the same​  I tried to add the button to the layout before inflating it, but I don't know how to get the layout : (Expected resource of type id error) Your code should be casting it to a relative layout and looking for a resource ID not a layout file. RelativeLayout rl = (RelativeLayout) getView().findViewById(R.id.fragment_main_layout); Hope this helps

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

    }

Android: onBackPressed() for Fragments - Daniel Wilson, Besides, for some cases I use replace to add my fragment to the stack, and Replace, add, replace fragment, then the Navigation Back button not working for​  When adding a Fragment to the back stack, Android developers most commonly use addToBackStack(null). Why do we always pass in null? It turns out we can pass in something else that makes the

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

Puzzle: Fragment stack pop cause issue on toolbar - Elye, Implement Custom Back Navigation; Activity onBackPressed() provide a Back button for this type of navigation, so you should not add a Back button for use in fragments or other lifecycle owners that have a shorter lifetime than the activity. But I unable to use toolbar back button to navigate back from fragments. Hardware back button works perfectly. I know that I need to override onOptionsItemSelected, catch android.R.id.home, check if there are something in back stack and than pop it. After changing fragment, "burger" button changes to "back arrow", but when I click on it

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().

Provide custom back navigation, There are two methods to add a back button on the toolbar. First, I'm gonna show you the modern method. This little code segment let you add a back arrow  All Android devices provide a Back button for this type of navigation, so you should not add a Back button to your app’s UI. Depending on the user’s Android device, this button might be a physical button or a software button. Android maintains a back stack of destinations as the user navigates throughout your application. This usually allows Android to properly navigate to previous destinations when the Back button is pressed.

Android Notes 24: How to add Back Button at Toolbar [UPDATED v2], Callback to a back button press event is received in the foreground Activity ( onBackPressed() event callback) which can be overridden and  Each fragment include a button and an input text box. When click the button it will either show a hidden or create a new target fragment. When click back menu, the stacked fragments will be popup by order, if the fragment is hide in the stack (fragment two), then the text in the input box will be saved also.

Android tutorial (2018) - 12, Handling the back button when fragments are involved can cumbersome. In this tutorial, we'll cover how to add fragments to backstack, handle  To handle Back Button in Android Fragments, you should consider addToBackStack() method as part of your FragmentTransaction. Below code can helpful to you during your android app development.

Handling back button press Inside Fragments, Just add a button on your fragment's layout file and add a click listener to it. Next, on onClick you can call getActivity().onBackPressed(); . This tutorial video for android beginners, they can just implements this back button on their project. in coming videos, i will make best to best videos for beginners, and they can understand

Comments
  • Well, then use addinstead of replace on the click method for cardview And you could handle the back button in that fragment specifically (detach fragment and popbackstack)
  • Thank you for you response, when i did that it display over the homeFragment
  • Well, that is the point.. This way you have homeFragment behind current one (like a stack) and it won't get reloaded(homeFragment i mean)
  • Thanks Ionut but im having issues detaching the HomeFragment so when i click on the card the home fragment and the targets page are displayed on the same UI any pointers?
  • Thanks you for replying, i tried out your solution it sill ended up reloading the homeFragment again
  • Thanks for responding Vir, i actually only want the back behaviour on that particular fragment
  • Thanks ill check it out hopefully its helpful
  • Thank you for your response @Radhey i tried your solution and i get this error java.lang.IllegalStateException: FragmentManager is already executing transactions
  • google on this exception brother! it is common error, I can provide you line to line code but it will note increase your knowledge.
  • Thanks Bro ill do that and come back when i get a solution