Search code examples
androidandroid-fragmentsback-button

How to go the previous fragment on the click of the back button of phone in android?


I want to go back to the previous fragment.I tried many method like addtobackstack(null) and all. But I did not get the solution. My problem is when I click on the back button it goes to the home fragment. But I did not want it. I want that when I click on the back button it go to the previous fragment. Can anyone tell me how can I do this ?

This is my onActivityCreated() method :-

 @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            getView().setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View view, int i, KeyEvent keyEvent) {
                    if (i == KeyEvent.KEYCODE_BACK) {

                        getFragmentManager().popBackStack();
                        return true;


                    }


                    return false;
                }
            });

        }

This is the first Fragment :-

 Fragment fragment = new Packages();
 getActivity().getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.container, fragment).addToBackStack(null).commit();

This is the second fragment :-

  Fragment fragment = new DeliveryFrag();
 mContext.getActivity().getSupportFragmentManager()
                            .beginTransaction()
                            .replace(R.id.container, fragment).addToBackStack(null)
                            .commit();

This is the third Fragment :-

Fragment fragment = new paytm();
   getActivity().getSupportFragmentManager().beginTransaction()
                                        .replace(R.id.container, fragment).addToBackStack(null)
                                        .commit();

I am doing the get the view and apply set onClickListner on it. but the program not enter in this method. I don't know why? Please can anyone tell me what I am doing wrong?


Solution

  • you should call this method in onResume. like this:

     @Override
        public void onResume() {
            super.onResume();
    
            getView().setFocusableInTouchMode(true);
            getView().requestFocus();
            getView().setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
    
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
    
                        getFragmentManager().popBackStack();
                        return true;
                    }
    
                    return false;
                }
            });
    
        }